$elemMatch 和 $in 之间的区别

Difference between $elemMatch and $in

我正在使用 mongoose 和 nestjs 构建一个聊天应用程序。这是我第一次尝试使用 mongo 作为数据库,所以我无法区分我应该使用哪个 mongo 查询。

以下功能是查找登录用户和其他用户之间的一对一聊天。我在 Insomnia 中测试了这两种方法,它们返回相同的结果。

方法一

async findOneOnOneChat(currentUserId, userId) {
  const oneOnOneChat = await this.chatModel
    .find({
      isGroupChat: false,
    })
    .and([
      { users: { $elemMatch: { $eq: currentUserId } } },
      { users: { $elemMatch: { $eq: userId } } }
    ])
  return oneOnOneChat;
}

方法二

async findOneOnOneChat(currentUserId, userId) {
  const oneOnOneChat = await this.chatModel
    .find({
      isGroupChat: false,
    })
    .and([{ users: { $in: userId } }, { users: { $in: id } }])
  return oneOnOneChat;
}

所以我的问题是这两种方法有什么区别?哪种方法更好?或者有没有更好的版本可以实现我想要的?

这些是不同的东西。

userId 是数组时使用 {users: { $in: userId } },并且您希望 user 值匹配 userId 中的一个或多个元素。在这种情况下,user 可以是单个值或值数组,但 userId 必须是数组。您可以将其视为 userId 上的循环,即针对 userId 中的每个元素在 user.

中搜索匹配项

使用 { users: { $elemMatch: { $eq: userId } } },其中 users 是数组,userId 是单个值。您可以将其视为 users 上的循环,即针对 users 中的每个元素搜索等于 userId.

的匹配项