$replaceRoot in mongodb aggregation

前端 未结 2 1811
孤城傲影
孤城傲影 2021-01-21 17:15

I have a collection like this:

{
    \"_id\" : ObjectId(\"5bd1686ba64b9206349284db\"),
    \"type\" : \"Package\",
    \"codeInstances\" : [ 
        {
                  


        
2条回答
  •  离开以前
    2021-01-21 17:23

    You just need to project for name and description instead of whole codeInstances. Check below

    db.collection.aggregate([
      { $unwind: "$codeInstances" },
      { $match: { "codeInstances.name": "b", "type": "Package" }},
      { $project: {
          "name": "$codeInstances.name",
          "description": "$codeInstances.description",
          "_id": 0
      }}
    ])
    

    Output:

    [
      { "description": "b1", "name": "b" },
      { "description": "b2", "name": "b" },
      { "description": "b3", "name": "b" }
    ]
    

提交回复
热议问题