Mongo convert embedded document to array

前端 未结 3 1767
遥遥无期
遥遥无期 2020-12-18 10:50

Is there a way to convert a nested document structure into an array? Below is an example:

Input

\"experience\" : {
        \"0\" : {         


        
3条回答
  •  忘掉有多难
    2020-12-18 11:17

    For mongoDB version >4.2 :

    db.doc.aggregate([{ $match: {'experience.0': { $exists: false } } },
        {$project:{experience:["$experience.0"]}}, { $merge: { into: "doc", on: "_id" }
    ])
    

    Note : Here we're merging the updated field/document with existing, but not replacing/updating entire document, default behavior of $merge is merge whenMatched document is found, You can pass other options like replace/keepExisting etc.

    Ref: $merge

提交回复
热议问题