changing field in a set object in mongodb - mongodb

I have this document in mongo:
{
id: objectId,
list: [
{
id: internalObjectId1,
enabled: true
},
{
id: internalObjectId2,
enabled: false
}]
}
I need to change the enabled field. How can I do it?

Use the positional $ operator. Suppose you have the following document in the collection whose list element value is an array of embedded documents:
{
"_id" : ObjectId("551be1a04db8a16ac729432e"),
"list" : [
{
"id" : ObjectId("54f43159c922ac0b4387ef9c"),
"enabled" : true
},
{
"id" : ObjectId("54f43159c922ac0b4387ef9d"),
"enabled" : false
}
]
}
The following will update the value of the enabled field in the embedded document with the id of 54f43159c922ac0b4387ef9d to true:
db.collection.update(
{
"_id": ObjectId("551be1a04db8a16ac729432e"),
"list.id": ObjectId("54f43159c922ac0b4387ef9d")
},
{
"$set": {"list.$.enabled": true}
}
)

Related

mongo updateMany $set nested array when some docs do not contain the path

I have a seemingly straight forward query to update the names of like objects in a mongo doc. But it fails as not all docs have comment.. what should i be looking for in the docs get around this and update only the docs that have likes on comments?
return this.model.updateMany(
{
comments: {
$exists: true
}
},
{
$set: {
'comments.likes.$[like].actor.firstName': user.firstName,
'comments.likes.$[like].actor.lastName': user.lastName,
},
},
{
multi: true,
arrayFilters: [
{ 'like.actor.username': user.username },
],
},
);
The problem is that not all comments are liked.. so then the query complains:
WriteError: The path 'comments.likes' must exist in the document in order to apply array updates.
Full output:
WriteError: The path 'comments.likes' must exist in the document in order to apply array updates.
Details:
WriteError({
"index" : 0,
"code" : 2,
"errmsg" : "The path 'comments.likes' must exist in the document in order to apply array updates.",
"op" : {
"q" : {
"comments" : {
"$exists" : true
}
},
"u" : {
"$set" : {
"comments.likes.$[like].actor.firstName" : "GGGJOHN",
"comments.likes.$[like].actor.lastName" : "Carmichael"
}
},
"multi" : true,
"upsert" : false,
"arrayFilters" : [
{
"like.actor.username" : "john.carmichael"
}
]
}
})
WriteError#src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults#src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch#src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute#src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.updateMany#src/mongo/shell/crud_api.js:655:17
#(shell):1:1
Here is an illustration of the doc in q, where comments is an array and the likes on a single comment is also an array:
what if you added
under match part of the update part query you are checking if likes attribute exists in the comments object
return this.model.updateMany(
{
"comments.likes": { // <---
$exists: true
}
},
{
$set: {
'comments.likes.$[like].actor.firstName': user.firstName,
'comments.likes.$[like].actor.lastName': user.lastName,
},
},
{
multi: true,
arrayFilters: [
{ 'like.actor.username': user.username },
],
},
);

How to update Meteor array element inside a document

I have a Meteor Mongo document as shown below
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "b1#gmail.com",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I want to update a specific array element's email with custom generated id using Meteor query something like the below.
for instance, I want to update the document
if 'users.id' == "b1#gmail.com" then update it to users.id = 'SomeIDXXX'
So updated document should looks like below.
{
"_id" : "zFndWBZTvZPgSKXHP",
"activityId" : "aRDABihAYFoAW7jbC",
"activityTitle" : "Test Mongo Document",
"users" : [
{
"id" : "SomeIDXXX",
"type" : "free"
},
{
"id" : "JqKvymryNaCjjKrAR",
"type" : "free"
},
],
}
I have tried the below but didnt work.
Divisions.update(
{ activityId: activityId, "users.id": emailId },
{ $set: { "users": { id: _id } } }
);
Can someone help me with the relevant Meteor query ? Thanks !
Your query is actually almost right except for a small part where we want to identify the element to be updated by its index.
Divisions.update({
"activityId": "aRDABihAYFoAW7jbC",
"users.id": "b1#gmail.com"
}, {
$set: {"users.$.id": "b2#gmail.com"}
})
You might need the arrayFilters option.
Divisions.update(
{ activityId: activityId },
{ $set: { "users.$[elem].id": "SomeIDXXX" } },
{ arrayFilters: [ { "elem.id": "b1#gmail.com" } ], multi: true }
);
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
You need to use the $push operator instead of $set.
{ $push: { <field1>: <value1>, ... } }

How to write a query to get all documents where field doesn't matches

I am having some trouble writing a query where I want to get all documents where they don't have a single subdocument where its property IsCurrentRevision is true. In other words, only getting documents that don't have a single revision marked as current.
What I have so far is:
{StartTimeUtc: {$gte: new ISODate('12/14/2019')},
EndTimeUtc: {$lte: new ISODate('01/21/2020')},
IsDeleted: false, 'MyDocument.IsCurrentRevision': false,
"MyDocument.1.IsCurrentRevision" : {$exists: false}}
This gets me somewhere, but the issue is that I have to manually query the index. In this case, the above query returns all documents with only 1 revision (so only one element in the sub document array), that doesn't have its revision marked as current. Thus if I wanted to get documents that have 2 revisions, with the second one marked as false as well I would need to update the query to be:
{StartTimeUtc: {$gte: new ISODate('12/14/2019')},
EndTimeUtc: {$lte: new ISODate('01/21/2020')},
IsDeleted: false, 'MyDocument.1.IsCurrentRevision': false,
"MyDocument.2.IsCurrentRevision" : {$exists: false}}
This is obviously tedious, is there a better way? If it helps, I am using Mongo Compass
Edit:
Here is how my document looks like
{
_id: Guid,
TemplateId: guid,
StartTimeUtc: DateTime,
EndTimeUtc: DateTime
..
..
SoapNoteRevisions: Array {
_id: Guid,
IsCurrentRevision: boolean,
..
..
}
}
I got rid of the unneeded bits as the document itself has a fair bit of fields within the revision as well (another sub array)
If you need documents where MyDocument elements/objects doesn't have IsCurrentRevision : true, try below query :
db.collection.find({'MyDocument.IsCurrentRevision': {$ne : true}})
If using aggregation :
db.collection.aggregate([{$match : {'MyDocument.IsCurrentRevision': {$ne : true}}}])
Collection Data :
/* 1 */
{
"_id" : ObjectId("5e27282ad02e05b69498b814"),
"MyDocument" : [
{
"IsCurrentRevision" : false
},
{
"IsCurrentRevision" : false
},
{
"IsCurrentRevision" : false
}
]
}
/* 2 */
{
"_id" : ObjectId("5e272839d02e05b69498b947"),
"MyDocument" : [
{
"IsCurrentRevision" : true
},
{
"IsCurrentRevision" : true
},
{
"IsCurrentRevision" : true
}
]
}
/* 3 */
{
"_id" : ObjectId("5e272846d02e05b69498ba5c"),
"MyDocument" : [
{
"IsCurrentRevision" : false
},
{
"IsCurrentRevision" : true
},
{
"IsCurrentRevision" : false
}
]
}
Result :
/* 1 */
{
"_id" : ObjectId("5e27282ad02e05b69498b814"),
"MyDocument" : [
{
"IsCurrentRevision" : false
},
{
"IsCurrentRevision" : false
},
{
"IsCurrentRevision" : false
}
]
}

How to update a field value in array in mongo database?

How can we update a value for 'Enabled' field in Configuration at index 1 in Configurations Array in mongo database ?
Below is my Json data.
{
"Configurations" : [
{
"Configuration" : {
"Host" : "",
"Port" : "1521",
"Enabled" : "true"
}
},
{
"Configuration" : {
"Host" : "",
"Port" : "",
"Enabled" : "true"
}
}
],
"Description" : "Check Database Server"
}
Is there any way to update value for Enabled field in Configuration ??
How can we update a value for 'Enabled' field in Configuration at index 1 in Configurations Array in Mongodba ?
I want to update Enabled field value of 2nd configuration in Configurations Array.
What about something like this
db.collection.update({},
{ "$set": { "Configurations.1.Configuration.Enabled": false }}
)
Try this:
db.collection.update({
"Configurations": {
"$elemMatch": {
"Configuration.Port": "1521"
}
}
}, {
"$set": {
"Configurations.$.Configuration.Enabled": "false"
}
})

update query in mongo db

I am using mongodb database to save the records.
This is one sample record:
"_id" : ObjectId("53870ed7e4b00e612650c1b8"),
"_class" : "mkcl.os.transformer.PayloadObject",
"formId" : NumberLong(50),
"dataMap" : {
"240" : "ramanbaug",
"241" : "1234",
"242" : "12345678",
"243" : "mr.joshi",
"244" : "8308009391 ",
"245" : "anuja2487#gmail.com",
"280" : "456",
"287" : "1234",
"276" : "29/05/14",
"247" : "No",
"248" : "No",
"249" : "Yes",
"250" : "No",
"251" : "Yes",
"252" : "No"
}
Now I want to update the value of field "241". I read about the Update and FindAndModify Query. But There is no error and records are not getting updated.
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
in the place of enter same query as you use to find that record(s), which you want to update
in the place of enter new values, like doing during insert query
and there are 3 more options:
upsert = Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found. So if your doc will not be found you will create a new one
multi = Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. For additional information, see Multi Parameter.
writeConcern = Optional. A document expressing the write concern. Omit to use the default write concern.
you can read more about write concern here: http://docs.mongodb.org/manual/core/write-concern/
Single document update example:
db.people.update(
{ name: "Andy" },
{
name: "Andy",
rating: 1,
score: 1
},
{ upsert: true }
)
check out for upsert: true, so it will create new doc if none found by name=Andy
Multi documents update example:
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)
Example with your data:
db.people.update(
{ _id: ObjectId("53870ed7e4b00e612650c1b8") },
{
dataMap: {
"241": "321"
}
}
)
that should work.
It's all in official documentation:
http://docs.mongodb.org/manual/reference/method/db.collection.update/
db.payloadObject.update({"dataMap.241":'1234'},{$set :{"dataMap.241":'123456'}});