如何按 mongodb 聚合中的订单计数?

How to get count by order in mongodb aggregate?

我有两个集合名称 listingsmoods

listings 样本:

{
    "_id": ObjectId("5349b4ddd2781d08c09890f3"),
    "name": "Hotel Radisson Blu",
    "moods": [
      ObjectId("507f1f77bcf86cd799439010"),
      ObjectId("507f1f77bcf86cd799439011")
    ]
}

moods样本:

{
    "_id": ObjectId("507f1f77bcf86cd799439011"),
    "name": "Sports"
},
{
    "_id": ObjectId("507f1f77bcf86cd799439010"),
    "name": "Spanish Food"
},
{
    "_id": ObjectId("507f1f77bcf86cd799439009"),
    "name": "Action"
}

我需要这张唱片。

{
    "_id": ObjectId("507f1f77bcf86cd799439011"),
    "name": "Sports",
    "count": 1
},
{
    "_id": ObjectId("507f1f77bcf86cd799439010"),
    "name": "Spanish Food",
    "count": 1
},
{
    "_id": ObjectId("507f1f77bcf86cd799439009"),
    "name": "Action",
    "count": 0
}

我需要这种记录。我不知道聚合。

做了这个工作:

db.collection.aggrate().count() 

尝试组合这些功能,它可能会起作用。

您可以使用 aggregate()

  • $lookup加入collectionlistings
  • $match 管道检查 moods listings 字段中的 _id moods 数组
db.moods.aggregate([
  {
    "$lookup": {
      "from": "listings",
      "as": "count",
      let: { id: "$_id" },
      pipeline: [
        {
          "$match": {
            "$expr": { "$in": ["$$id", "$moods"] }
          }
        }
      ]
    }
  },
  • $addFields to add count on the base of $size of array count 我们从上面的 lookup
  • 得到的
  {
    $addFields: {
      count: { $size: "$count" }
    }
  }
])

Playground