How to flatten a subdocument into root level in MongoDB?

后端 未结 6 1005
一个人的身影
一个人的身影 2020-12-01 13:53

For example, if I have a document like this

{
  a: 1,
  subdoc: {
          b: 2,
          c: 3
          }
}

How can I convert it into a

6条回答
  •  悲&欢浪女
    2020-12-01 14:38

    You can do this with the use of $set and $unset

    db.collection.update({},{ $set: { "b": 2, "c": 3 }, $unset: { "subdoc": 1 } })
    

    Of course if there are lots of documents in the collection, then much as above you need to loop the collection documents in order to get the values. MongoDB has no way of referring to a value of a field in an update operation alone:

    db.collection.find({ "subdoc": {"$exists": 1 } }).forEach(function(doc) {
        var setDoc = {};
        for ( var k in doc.subdoc ) {
            setDoc[k] = doc.subdoc[k];
        }
        db.collection.update(
            { "_id": doc._id },
            { "$set": setDoc, "$unset": "subdoc" }
        );
    })
    

    That also employs some safe usage of $exists in order to make sure you are selecting documents where the "subdoc" key is actually there.

提交回复
热议问题