I want to query all the items in my posts collection to find the newest comments. Currently each post has an embedded collection of comments like so
{ "_id" : ObjectId("4f84b8da6c33f31122000001"), "comments" :
[{
"uname" : "bargledoofus",
"msg" : "hello hello hello",
"_id" : ObjectId("4fe926fa811ec70100008888"),
"date" : ISODate("2012-06-26T03:05:30Z")
},
{
"uname" : "bargledoofus",
"msg" : "moar hello",
"_id" : ObjectId("4fe9272b2f1efb0100000078"),
"date" : ISODate("2012-06-26T03:06:19Z")
},
{
"uname" : "bargledoofus",
"msg" : "most hello ever",
"_id" : ObjectId("4fe92cfd7614c8010000002b"),
"date" : ISODate("2012-06-26T03:31:09Z")
},
{
"uname" : "bargledoofus",
"msg" : "i think i've got it",
"_id" : ObjectId("4fe92d04f4a35c010000000e"),
"date" : ISODate("2012-06-26T03:31:16Z")
}
]}
How would I query the posts collection for the latest comments, comments newer than a certain datetime, or by a comment attribute such as comment.uname?
Can I use map reduce somehow to accomplish this?
I am not sure if it is possible return just the comments with the current schema. But you can return all posts with comments that match a certain criteria. MongoDB’s db.find() matches documents and not embedded documents. You could do a:
db.posts.find({"comments.date":{$gt:<insert date object>}})It will return all the posts with all the comments that contain comments greater than the date specified but will also return other comments for that post as well.
A couple of options you may have are:
relevant comments in your query