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 ?
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}
]}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.