MongoDB查询包含两个指定用户ID的成员数组对话
查询两个用户间已存在的对话
你的Conversation模型结构:
{ members: { type: [ { username: String, email: String, id: String, avatar: String, }, ], }, }
此前查询单个用户对话的有效语句:
db.collection.find({ members: { $elemMatch: { id: userID } }, })
要筛选出同时包含user1ID和user2ID的对话,有两种简洁可行的写法:
方法一:使用$all结合$elemMatch
这种写法明确指定数组中需存在分别匹配两个用户ID的元素:
db.collection.find({ members: { $all: [ { $elemMatch: { id: user1ID } }, { $elemMatch: { id: user2ID } } ] } })
方法二:直接针对嵌套字段使用$all
因为members.id是每个成员的唯一标识,可简化为:
db.collection.find({ "members.id": { $all: [user1ID, user2ID] } })
两种写法都能准确查询出两个用户之间已存在的对话,第二种更简洁高效。
内容的提问来源于stack exchange,提问作者Grambam
相关产品推荐
相关产品推荐

