【问题标题】:How to find document that contains array with two equal values?如何找到包含具有两个相等值的数组的文档?
【发布时间】:2019-11-07 21:02:18
【问题描述】:

我有参与者数组的聊天集合

    [{
    "_id": ObjectId("5d12b2a10507cfe0bad6d93c"),
    "participants": [{
            "_id": ObjectId("5ce4af580507cfe0ba1c6f5b"),
            "firstname": "John",
            "lastname": "Anderson",
            "icon": "/assets/images/avatars/small/2.jpg"
        },
        {
            "_id": ObjectId("5ce4af580507cfe0ba1c6f5b"),
            "firstname": "John",
            "lastname": "Anderson",
            "icon": "/assets/images/avatars/small/2.jpg"
        }
    ]
}, {
    "_id": ObjectId("5d1124a50507cfe0baba7909"),
    "participants": [{
            "_id": ObjectId("5ce4af580507cfe0ba1c6f5b"),
            "firstname": "John",
            "lastname": "Anderson",
            "icon": "/assets/images/avatars/small/2.jpg"
        },
        {
            "_id": ObjectId("5ce54cb80507cfe0ba25d74b"),
            "firstname": "Milosh",
            "lastname": "Jersi",
            "icon": "/assets/images/avatars/small/3.jpg"
        }
    ]
}]

我通过 req.db.collection('chats').findOne({'participants._id': {$all: [req.userID, new mongo.ObjectID(req.params.to)]}}); 其中 userID 也是 ObjectID 并且等于。

通常它有不同的参与者,但我们的用户也可以向自己发送消息,这是许多社交网络中允许的选项。 因此,在这种情况下,我们的用户“John Anderson”向自己发送了消息,我们为其插入了聊天文档。

现在我遇到了问题,如何获取具有相等数组值的文档

{'participants._id': { '$all': [ 5ce4af580507cfe0ba1c6f5b, 5ce4af580507cfe0ba1c6f5b] }}
// return every chat contains our id in atleast one field, but we need both to be equal
// same for $in

{'participants._id': { '$eq': [ 5ce4af580507cfe0ba1c6f5b, 5ce4af580507cfe0ba1c6f5b] }}
// return nothing

我还能做什么?

【问题讨论】:

  • 你能用聊天数据分享你的收藏吗?
  • 我在帖子中更新了第一个代码块,是聊天集合的数据,只是在聊天中包含用户数组的文档

标签: mongodb


【解决方案1】:

您可以使用聚合框架实现此目的,使用 $group 阶段。首先,按chat._id 分组并使用$addToSet 仅将唯一用户保留在新数组中,然后添加过滤器以仅保留一个参与者的文档:

db.collection.aggregate([
  {
    "$unwind": "$participants"
  },
  {
    "$group": {
      "_id": "$_id",
      "participants": {
        "$addToSet": "$participants._id"
      }
    }
  },
  {
    "$match": {
      "participants": {
        "$size": 1
      }
    }
  }
])

结果:

[
  {
    "_id": ObjectId("5d12b2a10507cfe0bad6d93c"),
    "participants": [
      ObjectId("5ce4af580507cfe0ba1c6f5b")
    ]
  }
]

您可以在线试用:mongoplayground.net/p/plB-gsNIxRd

【讨论】:

  • 谢谢,我觉得这么简单的任务有点麻烦,但可能 mongo 没有其他方法(但它也找到与一个参与者的所有聊天,我如何通过某些参与者过滤它[0]。 _id?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多