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
//[{"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
CodePudding user response:
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.
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"]}}}}}])