I'm using MongoDB v4.2.13. I have a collection Transaction
with documents like this:
{
"id": 1,
"product": [
{
"name": "Book",
"price": 100
},
{
"name": "Pen",
"price": 10
}
]
}
Now I want to add a new field paid
into the first element of product
, which equal it's price
.
{
"name": "Book",
"price": 100,
"paid": 100
}
I try to use updating with aggregate pipeline $addFields
/$set
, but result is not as expected.
Query (I only want to use one query):
db.Transaction.updateOne(
{ id: 1 },
[
{
$addFields: {
"product.0.paid": {
$arrayElemAt: ["$product.price", 0]
}
}
}
]
)
Expected result:
{
"id": 1,
"product": [
{
"name": "Book",
"price": 100,
"paid": 100
},
{
"name": "Pen",
"price": 10
}
]
}
Actual result:
{
"id": 1,
"product": [
{
"name": "Book",
"price": 100,
"0" : {
"paid" : 100
}
},
{
"name": "Pen",
"price": 10,
"0" : {
"paid" : 100
}
}
]
}
How to get the expected result?