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" } } }

user3807753
  • 59
  • 1
  • 1
  • 3
  • 1
    For some relevant discussion see: [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). – Stennie Jul 05 '14 at 20:45

1 Answers1

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:

Community
  • 1
  • 1
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
  • 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" }`. – Stennie Jul 05 '14 at 20:43
  • I need only comments posted by only userid '1' and "title" is "Post One" not all documents – user3807753 Jul 08 '14 at 05:18
  • i tested but not executed i don't need all nested array i need matched nested records only. – user3807753 Jul 09 '14 at 10:16