Add field of array element in MongoDB aggregation

后端 未结 2 879
野的像风
野的像风 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.

    0 讨论(0)
  • 2021-01-18 08:51

    You can use $let with $arrayElemAt to define temporary variable and then reference it to get text field:

    db.collection.aggregate([
        {
            $addFields: {
                text1: {
                    $let: {
                        vars: {
                            first: {
                                $arrayElemAt: [ "$arr", 0 ]
                            }
                        },
                        in: "$$first.text"
                    }
                }
            }
        }
    ])
    
    0 讨论(0)
提交回复
热议问题