Matthias Thaler
Matthias Thaler

Reputation: 41

Query array of subdocuments

I have a chatRooms collections like following:

{ "name" : "Room1", "users" : [  {  "userId" : 1 },  {  "userId" : 2 } ] }
{ "name" : "Room2", "users" : [  {  "userId" : 1 },  {  "userId" : 4 } ] }
{ "name" : "Room3", "users" : [  {  "userId" : 2 },  {  "userId" : 3 } ] }
{ "name" : "Room4", "users" : [  {  "userId" : 2 },  {  "userId" : 1 } ] }

Now I want the Room(s) where userId 1 and 2 is in. I should get Room 1 and 4.

I tried different things like

db.chatRooms.find({users: {$elemMatch: {userId: 1, userId: 2}}})

But nothing is working. Any Idea ?

Upvotes: 0

Views: 33

Answers (1)

Disposer
Disposer

Reputation: 6371

You should use $all operator

db.chatRooms.find({users: 
    {$all : [
       {$elemMatch: {userId: 1}}
      ,{$elemMatch: {userId: 2}}
    ]}
})

Simplified version

db.coll.find({users: 
    {$all : [
       {userId: 1}
      ,{userId: 2}
    ]}
})

Upvotes: 1

Related Questions