Reputation: 55
db.getCollection('test').update({
"b_id": "3"
},
{
"$push": {"books": {
"status": "available",
"shelf_id": "$shelf_id",
"rack_no": "$rack_no",
"book_id": new ObjectId()
}
}
})
shelf_id and rack_no are already available in the document. Here, I need to create the array "books" which includes status, shelf_id, rack_no and book_id.
I am not able to get the existing value of shelf_id and rack_no in this case. It considers $rack_id as string instead the value from the document. Please suggest a way.
Upvotes: 0
Views: 58
Reputation: 28366
Yes, you can do that in MongoDB 4.2, using the pipeline form of update, but not with $push.
Passing an array of pipeline stages as the second argument to update will allow you to use aggregation operators.
The $push aggregation operator behaves very differently from the $push update operator, so in a pipeline use $set
with $concatArrays
, like:
db.getCollection('test').update({
"b_id": "3"
},
[{$set:
{
books: {$concatArrays:[
"$books",
[{
"status": "available",
"shelf_id": "$shelf_id",
"rack_no": "$rack_no",
"book_id": new ObjectId()
}]
]}
}
}])
Upvotes: 1