Update with same document field in mongodb - mongodb

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" }}]
)

Related

Mongodb use foreach on query and update results its results

I have a mongo collection where a field is supposed to point to another document's id in the same collection, but instead it is pointing to its "number". I need to perform an update on them but I'm having some problems on forming the query. Could you help me?
The structure of the document is like this:
{
"_id": "269410e2-cebf-40f1-a81f-fdce34185cdc",
"number": 1471,
"alternativeLocationId": "9871",
"locationType": "DUMMY"
},
{
"_id": "2945b24a-b82f-45a9-ad06-a884379b5597",
"number": 9871,
"locationType": "MAIN"
}
So as asked, I'd need to make document with number 1471 "alternativeLocationId" to be "2945b24a-b82f-45a9-ad06-a884379b5597" instead of 9871 (Note that the referenced documents are not locationType "DUMMY" nor have this alternativeLocationId field).
The query I've done so far goes like this, but when executed its not doing any changes:
db.location.find({alternativeLocationId: {$exists:true}}).forEach(
function (loc) {
var correctLocation = db.location.findOne({number: loc.alternativeLocationId});
db.location.update(
{_id: loc._id},
{$set: {alternativeLocationId: correctLocation._id} }
);
}
);
As mentioned by user20042973 the issue was the type mismatch between alternativeLocationId and locationNumber, after converting the value to int when looking for it, it works perfectly.

Mongo adding a field to a specific object in an array of objects using updateOne during a bulkUpdateOps

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 } ] }

Doing a difficult mongoDB find

I need to find a document by an ID of a user which is in an array in that document, which looks like
{
"uuid": "000-000-000whatever",
users:
[
{
"id":"id1",
"role":"role1"
},
{
"id":"id2",
"role":"role1"
}
]
}
and while I know that for that i could in mongo do "users.id" as a filter, i don't have a clue on how to do it using bson from Go.
The smartest thing I could figure was something along the line of
bson.M{"users": bson.A{bson.M{"id":id}}}
but needless to say, it didn't work.
It's the "same" in Go too:
bson.M{"users.id": id}

mongodb update an existing field without overwritting

{
questions: {
q1: "",
}
}
result after updating:
{
questions: {
q1: "",
q2: ""
}
}
I want to add q2 inside questions, without overwritting what's already inside it (q1).
One solution I found is to get the whole document, and modify it on my backend, and send the whole document to replace the current one. But it seems really in-effiecient as I have other fields in the document as well.
Is there a query that does it more efficiently? I looked at the mongodb docs, didn't seem to find a query that does it.
As turivishal said, you can use $set like this
But you also can use $addFields in this way:
db.collection.aggregate([
{
"$match": {
"questions.q1": "q1"
}
},
{
"$addFields": {
"questions.q2": "q2"
}
}
])
Example here
Also, reading your comment where you say Cannot create field 'q2' in element {questions: "q1"}. It seems your original schema is not the same you have into your DB.
Your schema says that questions is an object with field q1. But your error says that questions is the field and q1 the value.

How to push list of object ids from another query into an array attribute of a document in MongoDB?

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.