1

How do I make this query in mongoDB?

{

_id: "*******"

content: "",

comments: [

{

key1: "1",

key2: "2"

},

{

key1: "sdfs",

key2: "sdfasdf"

}

]

}

For example, I use the data as below. I want to query the items in comments in condition {key1: 1, key2: 2}, and not return the whole record.

What should I do?

user1477622
  • 132
  • 7
edge_man
  • 11
  • 1

2 Answers2

3

You can try to this one

{ "comments.key1" : "1", "comments.key2" : "sdfasdf" }

You only need to use this when more than one field must be matched in the array element.

turankonan
  • 1,011
  • 6
  • 13
  • 1
    That won't work. This will match even if one comments has key1, and a *different* comment has key2. You need to use $elemMatch. – Thilo Jun 27 '12 at 00:12
1

You can query a subdocument on two fields using $elemMatch:

{ comments: { $elemMatch : { key1: 1, key2: 2 } } }

You cannot return just the selected subdocument. You'll get all of them. So you'll have to filter on the client side. (You can of course, exclude all other fields of the main document).

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656