简体   繁体   中英

Merge document to an array field using mongodb aggregation

I have a collection like;

{
    "_id": ObjectId("5f8069b848e54248f8302b18"),
    "topics": [{
            "_id": "123",
            "name": "ABC",
            "type": 0
        }, {
            "_id": "455",
            "name": "DFR",
            "type": 0
        }
    ],
    "topic": {
        "_id": "777",
        "name": "FFG",
        "type": 123
    }
}

Ho can I write an aggregation query to merge topic to topics?

Is topic always unique? (Ie: not already included in topics) If so you can just add it to the array.

https://mongoplayground.net/p/vKv_qjm3VNp

db.collection.aggregate([
  {
    "$project": {
      topics: {
        "$concatArrays": [
          "$topics",
          [
            "$topic"
          ]
        ]
      }
    }
  }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM