My database sample looks like this:
db={
"sample": [
{
current_book: "Aurthor",
upcoming_book: [
"Sigma",
"Rocky"
]
}
]
}
I am trying to update the current_book value to the first element of upcoming_book and remove that element from upcoming_book.
Desired Output:
[
{
"current_book": "Sigma",
"upcoming_book": [
"Rocky"
]
}
]
I attempted the following:
db.sample.update({
"upcoming_book.0": {
$exists: true
}
},
{
"$set": {
current_book: {
$arrayElemAt: [
"$upcoming_book",
0
]
}
},
"$pop": {
"upcoming_book": -1
}
})
However, it incorrectly updates the current_book value and removes the value from upcoming_book.
Output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"current_book": {
"$arrayElemAt": [
"$upcoming_book",
0
]
},
"upcoming_book": [
"Rocky"
]
}
]
I also attempted to use the aggregation pipeline:
db.sample.update({
"upcoming_book.0": {
$exists: true
}
},
[
{
$set: {
current_book: {
$arrayElemAt: [
"$upcoming_book",
0
]
}
}
},
{
"$pop": {
"upcoming_book": -1
}
}
])
But this resulted in an error:
fail to run update: (Location40324) Unrecognized pipeline stage name: '$pop'.