MongoDB - 使用聚合操作投影数组子字段

4

有了这个基本文件:

{
  "_id": "userID",
  "name": "User Name",
  "profiles": [
    {
      "level": 1,
      "bar": {
        "_id": "bar1ID",
        "name": "Bar Name"
      }
    },
    {
      "level": 1,
      "bar": {
        "_id": "bar2ID",
        "name": "Bar 2 Name"
      }
    }
  ]
}

我需要删除一些字段,并重新分配bar字段,使其仅包含_id
{
  "_id": "userID",
  "profiles": [
    {
      "level": 1,
      "bar": "bar1ID"
    },
    {
      "level": 1,
      "bar": "bar2ID"
    }
  ]
}

使用Mongo聚合框架与用户ID匹配


可能会有帮助:https://dev59.com/CW865IYBdhLWcg3wHK7u - G. Ghez
1个回答

6

使用.aggregate()方法。

管道中唯一的阶段是$project阶段,在其中使用$map操作符。

db.collection.aggregate([
    { "$project": { 
        "profiles": { 
            "$map": { 
                "input": "$profiles", 
                "as": "profile", 
                "in": { 
                    "level": "$$profile.level",
                    "bar": "$$profile.bar._id" 
                } 
            } 
        } 
    } }
])

返回哪些内容:

{
        "_id" : "userID",
        "profiles" : [
                {
                        "level" : 1,
                        "bar" : "bar1ID"
                },
                {
                        "level" : 1,
                        "bar" : "bar2ID"
                }
        ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接