Add field of array element in MongoDB aggregation

后端 未结 2 910
野的像风
野的像风 2021-01-18 08:02

I have a collection of documents containing an array of objects:

db.collection.insert({
    arr: [
      { id: 1, text         


        
2条回答
  •  我在风中等你
    2021-01-18 08:45

    One way to extract a field of an array element is to project the first element using $arrayElemAt in a $project stage, then to access the desired field, e.g. text, in a second $project stage:

    db.collection.aggregate([
      {
        $project: {
          elem1: {
            $arrayElemAt: ["$arr", 0]
          }
        }
      },
      {
        $project: {
          text1: "$elem1.text"
        }
      }
    ])
    

    Mongo Playground.

提交回复
热议问题