TIC TIC - 4 months ago 16
JSON Question

MongoDB - Query document by same field from multiple objects in array

I have a document that looks like this:

{
"_id" : "AouRpb5g2WR9sZe5z",
"participants" : [
{
"user" : "CYvApwRFADveqBqEY",
"unread" : false
},
{
"user" : "sgoinZkaHbqth8nPr",
"unread" : false
}
],
"createdAt" : ISODate("2016-07-23T04:06:53.748Z")
}


I need to be able to find the document that has both users
'CYvApwRFADveqBqEY'
and
'sgoinZkaHbqth8nPr'
. I was able to find all documents with one of the users with
elemMatch
, but couldn't figure it out for both, or if that's even the correct way.

Answer

With a find query with an $all, you can do :

db.device.find({
  "participants.user": {
    $all: ["CYvApwRFADveqBqEY", "sgoinZkaHbqth8nPr"]
  }
});

From the doc of $all :

The $all operator selects the documents where the value of a field is an >array that contains all the specified elements.

Comments