0
votes

Here I have two documents in that I need query to get title="post one" and comments: userid="1" i want to get only the comments with above criteria. not all comments.

` { "_id": ObjectId("53b7f2383ed7755c2400002e"), "title": "Post One", "author": "bob", "posted": ISODate("2014-07-05T12:40:24.0Z"), "pageViews": NumberInt(5), "comments": { "0": { "userid": "1", "text": "this is cool" }, "1": { "userid": "2", "text": "this is bad" }, "3": { "userid": "3", "text": "this is badexample" } "4": { "userid": "4", "text": "No Thanx" } "5": { "userid": "1", "text": "No Its Fine" } "6": { "userid": "1", "text": "Testing" } "7": { "userid": "1", "text": "No Its Fine ok not bad" } "8": { "userid": "1", "text": "Testing ddd" }

} } `

{ "_id": ObjectId("53b7f2383ed7755c2400002e"), "title": "Post Two", "author": "bob", "posted": ISODate("2014-07-05T12:40:24.0Z"), "pageViews": NumberInt(5), "comments": { "0": { "userid": "1", "text": "this is cool" }, "1": { "userid": "2", "text": "this is bad" }, "3": { "userid": "3", "text": "this is badexample" } "4": { "userid": "4", "text": "No Thanx" } } }

1

1 Answers

0
votes

Arrays in documents can be queried like this

db.posts.findOne({comments: { $elemMatch: { userid: 1}}, 'title':"post one"});

For more information see these questions: