For Examples,
{
"_id":ObjectId("6245131fdbcda3639d75c951"),
"username": "joy"
"data" : [
{
"_id" : ObjectId("6245131fdbcda3639d75c953"),
"value_1" : "hello1"
"value_2" : "thank you1"
},
{
"_id" : ObjectId("6245131fdbcda3639d75c954"),
"value_1" : "hello2"
"value_2" : "thank you2"
},
]
}
I want to edit one of data object and delete old one and push edited one
because i want to the edited object will be last index of array.
i want to get this result.
{
"_id":ObjectId("6245131fdbcda3639d75c951"),
"username": "joy"
"data" : [
{
"_id" : ObjectId("6245131fdbcda3639d75c954"),
"value_1" : "hello2"
"value_2" : "thank you2"
},
{
"_id" : ObjectId("6245131fdbcda3639d75c953"),
"value_1" : "change data from hello1"
"value_2" : "change data from thank you1"
},
]
}
I tried it but i got error.
db.getCollection('profile').update(
{username:"joy"},
{
{
"$pull": {"data":
{"_id": ObjectId("6245131fdbcda3639d75c953")}
},
},
{
"$push": {"data":
{
"_id" : ObjectId("6245131fdbcda3639d75c953"),
"value_1" : "change data from hello1"
"value_2" : "change data from thank you1"
}
},
}
})
How can i get the value? thank you. :)
CodePudding user response:
MongoDB will not allow multiple operations/operators in a single field, you can use update with aggregation pipeline starting from 4.2,
$filter
to iterate loop ofdata
array and filter the documents that are not equal to your input_id
,$concatArrays
to concat filtereddata
array and new object that you want to add in the last index ofdata
array
db.getCollection('profile').update(
{ username: "joy" },
[{
$set: {
data: {
$concatArrays: [
{
$filter: {
input: "$data",
cond: {
$ne: ["$$this._id", "6245131fdbcda3639d75c953"]
}
}
},
[
{
_id: "6245131fdbcda3639d75c953",
value_1: "change data from hello1",
value_2: "change data from thank you1"
}
]
]
}
}
}]
)