Hi,
Below is the data structure in orders collections
{"_id": "order1",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
{"version": 2, "value": ISODate()},
{"version": 3, "value": ISODate()},
]
},
{"_id": "order2",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
{"version": 2, "value": ISODate()},
]
},
{"_id": "order3",
"status": "completed",
"lineitems":
[
{"version": 1, "value": ISODate()},
]
},
{"_id": "order4",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
]
},
I have two queries,
- Remove the last element using $pop from lineitems only when the array size is greater than 1.
– I tried adding validators using $jsonschema to ensure that the array has minimum size of 1.
db.orders.updateMany({“status”:“pending”},{"$pop": {“lineitems”: -1}});
$pop failed with document validation error for order4. Is there anyway to flag order4 and do $pop on rest of the documents where lineitems size is greater than 1? Or is there an alternate option available?
- How do I target documents with status = “pending” in order collection and update line items array with new element depending on the size of the array within the document
{"_id": "order1",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
{"version": 2, "value": ISODate()},
{"version": 3, "value": ISODate()},
**{"version": 4, "value": ISODate()}** -- To Update. version will be the max of the array size within the document.
]
},
{"_id": "order2",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
{"version": 2, "value": ISODate()},
**{"version": 3, "value": ISODate()}**, -- To Update
]
},
{"_id": "order4",
"status": "pending",
"lineitems":
[
{"version": 1, "value": ISODate()},
**{"version": 2, "value": ISODate()},** -- To Update
]
},
```
Mongo version: 4.2