MongoDB聚合并在设置活动密钥时保留所有值

时间:2018-10-13 07:04:22

标签: mongodb mongoose aggregation-framework lookup

我希望从“项目”返回的所有值都正确,并且当存在匹配项时,我希望“ isActive”为真。

exports.listUserItems = function (req, res) {

  // Aggregate results
  User.aggregate([{
      "$match": {
          "username": req.params.username
      }
  }, {
      "$lookup": {
          "from": "Items",
          "localField": "itemIds",
          "foreignField": "_id",
          "as": "items"
      }
  }, {
      "$unwind": {
          "path": "$items"
      }
  }, {
      "$project": {
          "item": "$items.item_name",
          "isActive": '1',
          "_id": 0
      }
  }], (err, result) => res.json(result));
};

实现此目标的最佳方法是什么?

我要分别返回所有项目和用户项目,然后将它们与object.value进行比较,等等。可以在模型方面完成吗?

我无法发布文档结构,因为stackoverflow不允许我这样做,但是您应该明白这一点。

编辑:

用户文档

{
    "username" : "anonuser",
    "items" : [ 
        ObjectId("5ba8345f1e56fe8e6caaaa07"), 
        ObjectId("5ba706d64e82292e72e9ae71")
    ]
}

然后我有一个“ Items”集合,其中包含3个这样的文档。

{
    "_id" : ObjectId("5ba706d64e82292e72e9ae71"),
    "item_name" : "Salary"
}

我期望的json api输出是

[{"_id":"5ba706d64e82292e72e9ae71","item_name":"Salary","isActive":true},{"_id":"5ba8345f1e56fe8e6caaaa07","item_name":"Fulltime","isActive":true},{"_id":"5ba9af6c1e56fe8e6cab521e","item_name":"Advisor","isActive":false}]

1 个答案:

答案 0 :(得分:2)

您可以尝试以下汇总

Items.aggregate([
  { "$lookup": {
    "from": "users",
    "let": { "itemsId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$itemsId", "$items"] }}},
      { "$project": { "isActive": { "$literal": true }}}
    ],
    "as": "items"
  }},
  { "$addFields": {
    "isActive": {
      "$ifNull": [{ "$arrayElemAt": ["$items.isActive", 0] }, { "$literal": false }]
    }
  }},
  { "$project": { "items": 0 }}
])