Add field of array element in MongoDB aggregation

后端 未结 2 881
野的像风
野的像风 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: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"
                    }
                }
            }
        }
    ])
    

提交回复
热议问题