You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:04:55