Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge array field in the documents in mongoldb

My documents looks like this

[{
 "updatedAt": {
        "$date": "2021-12-24T11:58:05.058Z"
    },
    "__v": 0,
    "slots": [{
        "isBooked": "true",
        "time": "11:15",
        "date": "2021-12-26"
    }]
},{
 "updatedAt": {
        "$date": "2021-12-24T11:58:05.058Z"
    },
    "__v": 0,
    "slots": [{
        "isBooked": "true",
        "time": "11:15",
        "date": "2021-12-26"
    }]
}]

When doing aggregate operation like below ,I am trying concat ,merge ,but nothin works

Staff.aggregate([
        {
            $match:{vendorId:payload._id,"slots.date": payload.serviceDate }
        }
,
       {
            $project:{
               
                _id:0,
                slots:1
            }
        },

       // { $project: { items: { $concatArrays:"$slots" } } }
      //  { $unwind: "$slots" },
       // {$group: { _id: "$slots"}},
       // { $merge : { into : "data", on: "slots" } },
      //  {$project: { _id: 0,slots: "$_id"} },
        

    ]) 

I am getting output like below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//[{"slots":[{"isBooked":"true","time":"11:15","date":"2021-12-26"}]},{"slots":[{"time":"08:00","date":"2021-12-26","isBooked":"true"}]}]

I want output something like below in a single slots array

[{"slots":[{"isBooked":"true","time":"11:15","date":"2021-12-26"},{"time":"08:00","date":"2021-12-26","isBooked":"true"}]}]

How to achieve this

>Solution :

Query

  • concat all the arrays of each document in the collection into a single array
  • group to get each array in [[...] [...]]
  • reduce and concat those to flatten them
  • concat is not accumulator so we need 2 steps group+reduce

*i don’t know if you need this, this will concat all arrays that pass the first match, also "slots.date": payload.serviceDate passes if the slots has at least one member that makes the filter true, if you want only those dates to keep, you need to filter first each array.

Test code

aggregate(
[{"$match":{"vendorId":payload._id,"slots.date": payload.serviceDate}}
 {"$group":{"_id":null, "slots":{"$push":"$slots"}}},
 {"$project":
  {"_id":0,
   "slots":
   {"$reduce":
    {"input":"$slots",
     "initialValue":[],
     "in":{"$concatArrays":["$$value", "$$this"]}}}}}])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading