This question already has answers here:
How do I update Array Elements matching criteria in a MongoDB document?
(2 answers)
Closed 4 years ago.
I have an object that looks like the following:
> db.delegate_list.find({"name": "delegateList"}).pretty()
{
"_id" : ObjectId("5becd1e0adeb2717c087cec5"),
"name" : "delegateList",
"delegates" : [
{
"address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafsdkjhc",
"sync" : false
},
{
"address" : "tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM",
"sync" : false
}
]
}
I am trying to update the sync field for specific object in the array. So for example if I update the sync field for the object at index 0 or address tz1SUgyRB8T5jXgXAwS33pgRHAKrafsdkjhc by doing the following it yields:
> db.delegate_list.update({"name":"delegateList"}, {$set:{"delegates.0.sync": true}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.delegate_list.find({"name": "delegateList"}).pretty()
{
"_id" : ObjectId("5becd1e0adeb2717c087cec5"),
"name" : "delegateList",
"delegates" : [
{
"address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc",
"sync" : true
},
{
"address" : "tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM",
"sync" : false
}
]
}
It works as expected, but if I perform the same update command to switch back sync:false, it gives me a malformed object, while deleting the rest of the array:
> db.delegate_list.update({"name":"delegateList"}, {$set:{"delegates.0.sync": false}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.delegate_list.find({"name": "delegateList"}).pretty()
{
"_id" : ObjectId("5becd1e0adeb2717c087cec5"),
"name" : "delegateList",
"delegates" : {
"address" : "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc",
"sync" : true,
"0" : {
"sync" : false
}
}
}
You can update specific array item, if item match your case using $ operator
db.delegate_list.update({"delegates.address":"tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc"}, {$set:{"delegates.$.sync": false}})
It will update the sync filed which address is "tz1SUgyRB8T5jXgXAwS33pgRHAKrafyg87Yc"
only, and not going to add any extra field.
Related
This question already has answers here:
How do you update objects in a document's array (nested updating)
(4 answers)
Mongodb: Finding and updating object property from array
(1 answer)
Closed 12 months ago.
{
"_id" : ObjectId("6221f3a818880f14e3c33040"),
"__v" : 0,
"createdAt" : ISODate("2022-03-04T11:10:32.753Z"),
"pm" : {
"checkList" : [
{
"ch_id" : "621eff4e0ed5c751adaa42fb",
"status" : "statu",
"dateMonthYear" : 1646286480139.0,
"val" : "Gopi",
"remarks" : "Good",
"_id" : ObjectId("6221f3a80a703519a4406e6c")
},
{
"ch_id" : "621eff4e0ed5c751adaa42fb",
"status" : "status",
"dateMonthYear" : 1646286480139.0,
"val" : "Gopi",
"remarks" : "Good",
"_id" : ObjectId("6221f3a80a703519a4406e6e")
}
]
},
"updatedAt" : ISODate("2022-03-04T11:56:59.662Z")
}
Above is the collection, and in that I need to update the checklist array inside pm object using "_id" as a find condition.
For example I need to change val and remarks of _id, ObjectId("6221f3a80a703519a4406e6e").
How to achieve this?
You can update a value in an array of nested objects in Mongoose
`db.users.update({"pm.checkList.ch_id" : "621eff4e0ed5c751adaa42fb"},{ $set:{
"pm.checkList.$.val" : "nop",
"pm.checkList.$.remarks" : "bed",
}})`
please try this way
using positional operation "$"
let collection = "deleted"
db.getCollection(collection).findOneAndUpdate({"data._id":ObjectId("5f2c0ebd7493c812cf59c52c")},{"$set":{"data.$.isDefault" : false}},{new:true})
I am trying to fetch total replies where read values for a replies is true. But I am getting count value as 3 but expected value is 2 (since only two read value is true) through Aggregation function available in Spring Data Mongo. Below is the code which I wrote:
Aggregation sumOfRepliesAgg = newAggregation(match(new Criteria().andOperator(Criteria.where("replies.repliedUserId").is(userProfileId),Criteria.where("replies.read").is(true))),
unwind("replies"), group("replies").count().as("repliesCount"),project("repliesCount"));
AggregationResults<Comments> totalRepliesCount = mongoOps.aggregate(sumOfRepliesAgg, "COMMENTS",Comments.class);
return totalRepliesCount.getMappedResults().size();
Using AND Operator inside Criteria Query and passed two criteria condition but not working as expected. Below is the sample data set:
{
"_id" : ObjectId("5c4ca7c94807e220ac5f7ec2"),
"_class" : "com.forum.api.domain.Comments",
"comment_data" : "logged by karthe99",
"totalReplies" : 2,
"replies" : [
{
"_id" : "b33a429f-b201-449b-962b-d589b7979cf0",
"content" : "dasdsa",
"createdDate" : ISODate("2019-01-26T18:33:10.674Z"),
"repliedToUser" : "#karthe99",
"repliedUserId" : "5bbc305950a1051dac1b1c96",
"read" : false
},
{
"_id" : "b886f8da-2643-4eca-9d8a-53f90777f492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
},
{
"_id" : "b56hy4rt-2343-8tgr-988a-c4f90598h492",
"content" : "dasda",
"createdDate" : ISODate("2019-01-26T18:33:15.461Z"),
"repliedToUser" : "#karthe50",
"repliedUserId" : "5c4bd8914807e208b8a4212b",
"read" : true
}
],
"last_modified_by" : "karthe99",
"last_modified_date" : ISODate("2019-01-26T18:32:41.394Z")
}
What is the mistake in the query that I wrote?
I want to create an index so that my DB does not allow me to insert documents whose value for the key lema is already present in some document of the DB. I did this:
db.version()
3.0.14
> db.rae.ensureIndex({"lema":1, unique: true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 2,
"note" : "all indexes already exist",
"ok" : 1
}
> db.rae.insert({"lema":"a"})
WriteResult({ "nInserted" : 1 })
> db.rae.insert({"lema":"a"})
WriteResult({ "nInserted" : 1 })
> db.rae.insert({"lema":"a"})
WriteResult({ "nInserted" : 1 })
> db.rae.find()
{ "_id" : ObjectId("591a0ce372329f3162a314cc"), "lema" : "a" }
{ "_id" : ObjectId("591a0ce472329f3162a314cd"), "lema" : "a" }
{ "_id" : ObjectId("591a0ce572329f3162a314ce"), "lema" : "a" }
Clearly the DB is letting me insert documents whose values of lema are all a. How can I fix this? Thanks a lot
From Stennie's comment:
I should use createIndex instead of ensureIndex. Also I had a mistake, I should use db.rae.createIndex({"lema":1}, { unique: true}).
I am trying to update an existing document which has a field with null value in it and I am getting the following error.
Document:
{
"_id" : ObjectId("582299f71e21dbf65027325e"),
"b" : "5555",
"f" : null
}
Query:
db.getCollection('temp').update({"b":"5555"},{"$set":{"f.1.b":1,"f.2.b":2}})
Error:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (f of f.1.b) to traverse the element ({f: null})"
}
})
Anyone can tell me why it was not updating the value in the document.
Thank you.
Because there are no f.1.b and f.2.b object found to set
In this case you can try this
Prepare a proper object and try to set
Eg :
var temp = {
1 : {b: 1},
2: {b : 2}
}
db.getCollection('temp').update({"b":"5555"},{"$set":{f:temp}})
I have this mongodb data i have stored in this way
db.orders.insert( { _id: ObjectId().str, name: "admin", status: "online",catalog : [
{
"objectid" : ObjectId().str,
"message" : "sold",
"status" : "open"
}
]})
and i am trying to update it in this manner db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$set: {"catalog.message": "added to cart"}})
and this is the error message i am getting
> db.orders.update({"_id":"5703b86df3d607cb5fa75ff3"},{$set: {"catalog.message": "added to cart"}})
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (catalog of catalog.message) to traverse the element ({catalog: [ { objectid: \"5703b86df3d607cb5fa75ff4\", message: \"sold\", status: \"open\" } ]})"
}
})
How can i update this record?.
According to MongoDB's Examples you should provide the index of the Object in the array which you want to update. Since you want to update the first object i.e. object in the array at index 0 use this :
db.orders.update(
{"_id":"5703b86df3d607cb5fa75ff3"},
{$set: {"catalog.0.message": "added to cart"}});