Update in mongodb, more than one way? - mongodb

Im trying to add a "role" to a document, which is an update command such as this:
db.users.update({username: 'someUser'},{'$set': {roles: ['user', 'admin']}});
To a document structured like this:
{
_id:'22222',
username : '',
roles: ['user']
}
Is there any other way of doing this except from the query above?

There are also $addToSet that adds to set and $pull that removes from set operators.
So your query may look like:
db.users.update(
{ username: 'someUser' },
{ $addToSet: { roles: 'admin' } }
);
UPD: As #Juan Carlos Farah mentioned there is also $push that appends value to array operator.

Related

how to update the name of multiple objects to lowercase in mongodb?

i need to update the all user who have the rol user and change the nickName to lowercase, i try with this code
const users = await userModel.updateMany({ rol:'user' },
{
$set:{
nickName: {
$toLower : "$nickName"
}
}
});
but is not working
In the future, please describe in what way your approach is not working. I went ahead and copied your example into this playground example and saw that your current approach resulted in the document being modified to include this field:
"nickName": {
"$toLower": "$nickName"
}
The problem here is that you are attempting to use the (aggregation) $set stage in your update (so that you can reference the existing $nickName field), but the update is using the $set (non-aggregation) modifier. If you wrap your second argument in square brackets (telling the database that you want to use an aggregation) then it should do what you want:
db.collection.update({
rol: "user"
},
[
{
$set: {
nickName: {
$toLower: "$nickName"
}
}
}
])
Playground demonstration here

MongoDB - how I add a UUID column to existing collection based on values from current entries?

I have 'Users' collection which has two columns, '_id' and 'userName', both of type string.
I want to add third column 'UserId' which will be UUID wrapping the id from _id column.
Tried few ways but without any success.
For example:
{
_id: "fe83f869-154e-4c26-a5db-fb147728820f",
userName: "alex"
}
I want it to be:
{
_id: "fe83f869-154e-4c26-a5db-fb147728820f",
userName: "alex",
UserId: UUID("fe83f869-154e-4c26-a5db-fb147728820f")
}
I tried something like:
db.Users_temp.update(
{},
{ $set: {"UserId": UUID("$_id") } },
false,
true
)
But it results in columns with value UUID("----")
Will appreciate any help.
Ok,
Found a solution to my problem.
db.Users_temp.find().forEach(function(user) {
db.Users_temp.update(
{"_id" : user._id},
{ "$set": {"UserId": UUID(user._id)} }
)
})
this will work
i am not sure why but this works only with set operation as an array rather than as a object
db.Users_temp.update({},[{$set: {'UserId': '$_id'}}])

How easy rename keys in mongodb arrays?

I have collection where documents have field as an array. I need to rename one field inside each item of this array, but in mongodb all variants looks very monstrous. I even try to use $[] but I can't refer to old value of object, only custom:
collection.update(
{ customField: { $exists: true } },
{
$set:
{
'payload.oneMoreField.$[].path': 'howReferToOldValue',
},
$unset:
{
'payload.oneMoreField.$[].way': '',
},
},
options
);
Somebody knows an easy way to just change the value of a key in monogodb ?

How to add ObjectId property to each object of an array

I am have manually created an object in a Mongo collection:
{
"messages": [
{
"url":"http://test.test.com",
"message":"test message"
}
],
....other properties
}
I would like to add an _id:ObjectId() to each item of my messages array and for each document in the collection.
I tried:
collection.update({}, {
$set: {
'messages.$._id': ObjectId(),
},
}, { multi: true }
but this is not working. The Id is getting added when I add new ones going through Mongoose, but these were manually entered into mongo. Any help is appreciated.
Your syntax is correct, but in order to use the $ positional operator the array field must appear as part of the query document, check in documentation.
Try this:
db.collection.update({messages: {$exists: true }},
{$set: { 'messages.$._id': ObjectId() } },
{multi: true}
)

Mongodb cursor to Json

So my problem is that I cant push a result of findOne() method to array in document.
For example, I want to add another user to some array (project participants) like this :
var user =db.users.findOne({_id:"123456"})
db.projects.update({_id:'abcde'},{$set:{$push:{participants:user}}})
how can I fix that ?
You need your update query like so:
db.test.update({
_id: 'abcde'
},
{
$push: {
participants: { name: 'Bob'}
}
})