I have a simple question and I don't know how to formulate it clearly because my english is bad I will explain with an example:
the MongoDB object is like this :
{_id:ObjectId("606445724bd1552e94f60691"),email:"exemple#gmail.com",password:"password123"}
I want to add age for example the object will be :
{_id:ObjectId("606445724bd1552e94f60691"),email:"exemple#gmail.com",password:"password123",age:30}
just like this please help
Simply
db.collection.updateOne(
{ _id: ObjectId("606445724bd1552e94f60691") },
{ $set: { age: 30 } }
)
Hopefully you don't store passwords as clear text in your database!
Related
Use case
Adding a field to a specific object in an array of objects using updateOne during a bulkUpdateOps
Blockers
I have been unable to find a way to identify and update a specific object in the subdocument array of a specific record.
I only have access to this DB through MongoDB Compass, and I plan to use the provided mongosh tool.
Data example
Our purchaseorders model looks like this:
{
_id: uuid,
...rest,
documents:[
{
_id:uuid,
forignKey2:string (optional),
keyIWantToAdd:string (optional),
...rest
}
]
}
So if I have
{
_id:*1,
documents:[
{
_id:*2,
forignKey2:'no-test',
...rest
},
{
_id:*3,
forignKey2:'test',
...rest
},
]
}
I want to add a key and value like this (really I'm willing to do anything to set these values, this is just the closest I have been able to get):
var bulkUpdateOps = db.purchaseorders.initializeOrderedBulkOp();
bulkUpdateOps.find('*1').updateOne({
$set:{
documents.[index of document object with forignKey2:'test' or _id:*3 whichever is easier].keyIWantToAdd:'valueIWantToAdd'
}
})
bulkUpdateOps.execute();
Any help or suggestions would be greatly appreciated.
#rickhg12hs posted exactly what I was looking for. For anyone else using mongodb.com/docs/manual/reference/method/Bulk.find.arrayFilters the bulk find is being ran on an array of objects like this: { grades:[ { grade: 85, mean: number } ] }
I have a this document.Which has a schema of below:
rental:{
total:Number,
due:Number
}
For example let us assume the document is filled with values like this:
rental:{
total:350,
due:10
}
I want to replace the value of 'total' to 'due'.So i want it to be like this:
rental:{
total:350,
due:350
}
I came accross $set,i did something like this:
PS:"User" is the name of the model.(which i havent refrenced here)
User.updateMany({},{$set:{'due':"$total"}},function(err,..}{
//do whatever
}
But this didnt work out.I ran into a CastError.
I also came accross '$replaceWith'.But i didnt understand a bit on how to use that in my case.Any help is appriciated.Thank you
You can use below query
db.collection.update(
{ },
[{ "$set": { "due": "$total" }}]
)
My user collection is defined to be permitted to look like this:
{
_id: String,
questions: [Object]
}
Inside the questions it will look like this (example):
[
{
questionId: 'f93uf0auf'
answer: ["yes", "maybe"]
},
{
questionId: 'avka+0uf'
answer: ["no"]
}
]
I'm trying to find a catch-all command to this collection and cover the following bases:
Should create the questions field if it doesn't exist.
Needs to create an array from the start because that is the only allowed format.
Should be able to add to the answer set.
I'd like to do something like this:
Users.update({_id: userId, 'questions.questionId': questionId}, {$addToSet: {'questions.$.answer': answer}})
However, this doesn't create the field if it doesn't exist. upsert doesn't work either.
Is there a catch-all command?
Are you sure your query criteria is really catching an object? And does the question object exist when you try to update it?
Because I have tested your update query, and it does create the answer field when it doesn't exist. The official documentation confirms that as well.
If the field is absent in the document to update, $addToSet creates the array field with the specified value as its element.
It used this very object to test it, adding the answer field to the second question successfully.
{
"_id" : ObjectId("56c9d76e2318c31cb70f9c55"),
"questions" : [
{
"questionId" : "f93uf0auf",
"answer" : [ "yes" ]
},
{
"questionId" : "f93uf0aug"
}
]
}
I cannot find one way to meet your requirement through $addToSet, here is one way to do that through command as bellow.
> db.questions
.find({_id: userId})
.forEach(function(doc) {
if (!doc.questions) {
doc['questions'] = []
};
var exist = false;
doc.questions.map(function(e) {
if (e.questionId && (e.questionId == questionId)){
e.answer.push(answer);
exist = true;
}
});
if (!exist) {
doc.questions.push({questionId: questionId, answer: [answer]});
}
db.questions.save(doc);
});
What I need is something like:
db.categories.update(
{ _id: ObjectId("52824e116a4dec0000000004") },
{ $push: { scores: { $each : db.products.find({"category": ObjectId("51cedfb29b33fc0800000015")})} }
)
Do I need ORM tool for this? Or can I do with shell?
You probably just want to use JavaScript in the shell. It might look something like this:
// not sure what your schema looks like, but you'll want your find to
// get you the right documents and format
var ids = db.products.find({"category": ObjectId("51cedfb29b33fc0800000015")});
db.categories.update(
{ _id: ObjectId("52824e116a4dec0000000004") },
{ $pushAll: { scores: ids }
}
);
You'll have to make sure that ids is an array of object ids. The current find you have looks like it will return the entire documents. If you need more guidance, I'd suggest adding your schema to your question as well.
I need to select users for corresponding data from query.
I have this collection in my DB (two or more rows are output of my query as well)
> db.Friends.find()
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "3MTmHcJNEzaaS8hrd","_id" : "aiRD.." }
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "SoTozuZ4nWooRBeFz","_id" : "QingX.." }
When it would be just one result as findOne(...) the second query would looks like this:
users.findOne({ _id: firstQueryResult.followeeId })
But now the problem is... how can i select the users from users collection when i dont have only one followeeId but more of them?
Please someone show me an example of code.
My research:
Is this a good solution?
friendsData.forEach(function(relationShip) {
followeeIds.push(relationShip.followeeId);
});
console.log(followeeIds);
Ok i finalllly figure out the problem.For next readers:
Check if autopublish is enabled or disabled.
If is disabled you need to publish the collection from the DB
Meteor.publish("userData", function () {
return Meteor.users.find({},
{fields: {'username': 1}});
});
PS: i want to publish only username field and thats all!
You need to subscribe the data as well!
Meteor.subscribe("userData");
Now you can access other users data this way:
users= Meteor.users.findOne({username: "Nolifer"});
To my original problem ... i will probably use this function for iterate over more then one row result(its more a SQL term but i am not sure what term use in mongoDb maybe a document? whatever):
users.forEach(function(user) {
console.log(user);
});
Thats it!
P.S.: I think there is nothing wrong on this but what i know right? :) So if someone know a better way please leave a comment. If not give me know if it was useful for you :)
According to the mongo manual, use the $in operand: http://docs.mongodb.org/manual/reference/operator/in/#op._S_in
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )