The requirement is to convert all sales
array properties to objects with their first elements' quantity value. The collection name is branches
and the example data is below.
[
{
"_id": 111,
"recs": [
{
"date": "01-01-2021",
"sales": [
{
"quantity": {
"P": 14,
"K": 0,
"U": 0
}
}
]
},
{
"date": "02-01-2021",
"sales": [
{
"quantity": {
"P": 23,
"K": 0,
"U": 0
}
}
]
}
]
},
{
"_id": 21,
"recs": [
{
"date": "01-01-2021",
"sales": [
{
"quantity": {
"P": 11,
"K": 0,
"U": 0
}
}
]
},
{
"date": "02-01-2021",
"sales": [
{
"quantity": {
"P": 31,
"K": 0,
"U": 0
}
}
]
}
]
}]
The expected response is below.
[
{
"_id": 111,
"recs": [
{
"date": "01-01-2021",
"sale": {
"P": 14,
"K": 0,
"U": 0
}
}
]
}]
I tried $map
, $addFields
but no way I couldn't find a solution.
CodePudding user response:
In $map
, you need:
$first
to query the firstsales.quantity
object inrecs.sales
array.$mergeObject
to merge the current document inrecs
array with the document from (1).
db.collection.aggregate([
{
"$project": {
_id: 1,
recs: {
"$map": {
"input": "$recs",
"in": {
"$mergeObjects": [
"$$this",
{
sales: {
$first: "$$this.sales.quantity"
}
}
]
}
}
}
}
}
])