简体   繁体   中英

Checking 2 fields in array and combine two arrays to get single array Mongodb

I have a collection

{
_id:"123",
obj1:[{defaultNo:1,fine:100},{defaultNo:3,fine:10}],
obj2:[{default:1},{default:2},{default:3}]
}

I tried something like this but I was stuck

db.collection.aggregate([
// Match possible documents
{ "$match": {
    "_id" : "123"
}},
{ "$unwind": "$obj1" },{
    "$group": {
    "_id": { 
        "document": "$_id", 
        "objfirst" : "$obj1.defaultNo",
        "objlast":"$obj2"
    },

} }  ])

This gave me a result of

   "_id" : {
                "document" : "123",
                "objfirst" : "1",
                "objlast" : [{default:1},{default:2},{default:3}]
},  "_id" : {
                "document" : "123",
                "objfirst" : "2",
                "objlast" : [{default:1},{default:2},{default:3}]
},

But i was looking for this type of result like merging two arrays with the field values

{
_id:"123",
object:[{default:1,fine100},{default:2,fine:false},{default:3,fine:10}]
}

I'd suggest you to look at $concatArrays operator which do what exactly are you looking for.

If you run following query in shell,

db.collection.aggregate([
  {$match:{_id:"123"}},
  {$project:{object:{$concatArrays:["$obj1","$obj2"]}}}
])

Output will be (matches closely your desired output using your sample input documents)

{ 
    "_id" : "123", 
    "object" : [
        {
            "default" : 1.0, 
            "fine" : 100.0
        }, 
        {
            "default" : 3.0, 
            "fine" : 10.0
        }, 
        {
            "default" : 1.0
        }, 
        {
            "default" : 2.0
        }, 
        {
            "default" : 3.0
        }
    ]
}

Update:

Added $match to aggregation pipeline to match OP's attempt.

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