0

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 Answer 1

0

Arrays in documents can be queried like this

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

For more information see these questions:

Sign up to request clarification or add additional context in comments.

3 Comments

Note that $elemMatch will only return the first matching element in an array for each document. So this won't work if you want to get all the comments matching { userid: 1 } in the post with { 'title' : "post one" }.
I need only comments posted by only userid '1' and "title" is "Post One" not all documents
i tested but not executed i don't need all nested array i need matched nested records only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.