I want to rename a field in MongoDB, then setting new Value with the old field Name: here is the example :
db.exemption.update({'ref':163},{$rename:
{'request.reference':'request.oldRef'},$set:
{'request.reference':'00000'}},true,true)
but heri the error that I got
{ [MongoError: Cannot update 'request.reference' and 'request.reference' at the same time]
name: 'MongoError',
code: 16837,
err: 'Cannot update \'request.reference\' and \'request.reference\' at the same time' }
Is there a possible way to do the update of this field inspite of using 2 queries mongo?
You could do
db.exemptions.update({ref: <value>}, {
$unset: {'request.oldRef': 1},
$set: {'request.reference': <new value>}
});
It doesn't really rename the field, but it gives you the same result.
Related
I have a string field which consists of date, I am trying to run following command mentioned in Update string to Date object in mongodb
db.getCollection('rft').updateMany(
{},[{ "$set": { "createdate": { "$toDate": "$create_date" } }}]
);
Getting an error:
Error: Failed to execute script.
Error: the update operation document must contain atomic operators
Details:
DBCollection.prototype.updateMany#src/mongo/shell/crud_api.js:625:1
#(shell):1:1
Can someone please help in updating the records to get new field with date time.
Your query seems to work as expected , check playgroud unless something different is expected ...
I am going through a course on MongoDB. Below is my list of documents in a collection called 'flightData'. Below is result of find query:
flights> db.flightData.find()
[
{
_id: ObjectId("611aaa1c4a0269583c8d81b0"),
aircraft: 'AirBus A308',
departingFrom: 'Mumbai',
arrivalStation: 'Moscow',
departureDate: '24/09/2021',
departureTime: '01:44',
arrivingAt: '12:00',
isOneWay: false,
status: {
description: 'on time',
lastUpdated: 'One hour ago',
details: { contact: 'John Doe' }
}
},
{
_id: ObjectId("611aaa554a0269583c8d81b1"),
aircraft: 'AirBus A308',
departingFrom: 'Kolkata',
arrivalStation: 'Stockholm',
departureDate: '24/09/2021',
departureTime: '01:44',
arrivingAt: '12:00',
isOneWay: false,
status: {
description: 'on time',
lastUpdated: 'One hour ago',
details: { contact: 'Cool User' }
}
}
]
When they show the difference between update and updateMany through an example similar to below one:
flights> db.flightData.update({_id:ObjectId("611aaa554a0269583c8d81b1")},{"delayed":false})
In the lecture it works. However, in my case it throws below error:
MongoInvalidArgumentError: Update document requires atomic operators
Can someone please explain this behavior? Is it not supported for my version or something else?
I am using MongoDB 5.0.2, mongosh 1.0.5
If you want to add the "delayed" field to the document you will want to use the $set operator
db.flightData.update({_id:ObjectId("611aaa554a0269583c8d81b1")},{$set:{"delayed":false}})
If you would like to replace the document you should use replaceOne
This command was added in mongodb 3.2 to avoid accidentality replacing the entire document when you mean to update a field
This may help someone so writing as answer.
In my case, I'm doing bulk write operation and missed a field that I'm trying to update in Mongoose Schema caused this issue. After correcting the Mongoose Schema, issue is resolved.
So, validate the fields that are used in update are configured in Schema if you are using Mongoose.
I'm trying to write a Mongo update query that updates a specific column and revises it using the current data in that field. So instead of:
$set: {
displayName: 'test'
}
I need to append something to the existing data like:
$set: {
displayName: 'test' + displayName
}
But the above syntax doesn't work - I'm just looking for the syntax to simply update a column to it's current value + 'test'.
There is no way for referencing document fields in update operation. You should move execution to the client and iterate cursor with forEach:
db.collection.find({ /* your query here */}).forEach(function(doc) {
db.collection.update({_id: doc._id}, {$set: {displayName: 'test' + doc.displayName}});
})
This Meteor server code tries to update Mongodb collection but gives error:
let originalDoc = original.fetch()[0];
Meteor.users.update(userId, {
$set: {
profile: originalDoc.profile,
cmpProfile: originalDoc.cmpProfile,
aaa: originalDoc.aaa
},
$unset: {
'profile.abc': 1
}
});
The error:
Exception while invoking method 'xyz' MongoError: Cannot update 'profile' and 'profile.abc' at the same time
Any ideas? thx
The error is pretty self-explanatory: you can't at the same time $set whole profile and $unset profile.abc because MongoDB does not allow such operations.
Instead of calling $unset you could do delete originalDoc.profile.abc; before running query and that will effectively remove abc field from profile as you're setting whole embedded document.
I am a relative newbie in mongodb but have lots of experience in MySQL.
I want to do a simple query that would appear in MySQL as follows:
UPDATE {database}.{table} SET {FIELD1}='{VALUE1}' WHERE {FIELD2} = {VALUE2};
e.g.
UPDATE test.user SET email='test#acc.ie' WHERE ref='12';
I don't want to destroy the database or collection on my first attempt.
I have only ever ran SELECT type queries on mongo, edited individual json entries or dropped an entire database. A select in mongodb looks like the following
db.getCollection('user').find({email : "test#acc.ie"})
Is the following correct based on the MySQL example?
db.user.update({ref : "12"}, {$set: {email: test#ac.ie}}, { multi: true })
Because this is the response I am getting:
Updated 0 record(s) in 141ms
The syntax looks ok, you will get an error with how you are accessing the collection currently, change it to
db.user.update({ref: 12}, {$set: {email: 'test#ac.ie'}}, { multi: true })
or
db.getCollection('user').update({ref: 12}, {$set: {email: 'test#ac.ie'}}, { multi: true })
Note: the value of the field being set should be quoted if it's a string and unquote if a number. Best read the manual for better referencing.