Updating multiple documents in mongodb using _id field - mongodb

I have sample products table and would like to update multiple documents using _id field. Every time, I try this it only updates the first doc in the $in clause I mentioned , not updating all.
db.products.update({_id:{$in:[ObjectId("507d95d5719dbef170f15bff"),
ObjectId("507d95d5719dbef170f15c01"), ObjectId("507d95d5719dbef170f15c00")]}},
{$set:{'monthly_price':7865}}, {multi:true})

You can first try running find on the products table to make sure that all the object ids actually exist.
You can also try explain command

give this a try:
db.<collection>.update( { query }, {$set: {monthly_price:7865}}, false, true)

I think the object id's which you have given doesn't exist in the collection.
I tried using the following query and it worked for me.
db.test.update({_id:{$in:[ObjectId("57b33483e5b9ce24f4910855"),
ObjectId("57b33483e5b9ce24f4910856"),
ObjectId("57b33489e5b9ce24f4910857"),
ObjectId("57b33491e5b9ce24f4910858")
]
}
},
{$set{'isCurrentStatus':true}},
{multi:true}
)

Related

MongoDB creating index on a new field

I need to create a TTL Index in MongoDB and for that, I'm adding a new field "last_modified". I'm using the latest Python and pymongo in case this makes any difference.
After reading information on sparse and non-sparse indexes I understand that all documents that do not have "last_modified" will have this field added with the null value.
Is there a way to set some default value instead of null for those documents?
Alternatively, I'll have to update all documents in all DB instances using some migration function, but I would really like to do it clean...
Thanks in advance for any links or ideas!
I understand that all documents that do not have "last_modified" will have this field added with the null value.
No this is not true, sparse indexes just index documents where the field exists. documents without this field will just be out of the index converage.
Is there a way to set some default value instead of null for those documents? ... I'll have to update all documents in all DB instances ... to do it clean...
You have to run an update, there is no magic solution. Not sure why doing this is "not clean".
The update is super simple:
// this query will allow you to execute the update even if you started streaming new events with this field.
db.collection.updateMany({ last_modified: {$exists: false} }, { $set: { last_modified: defaultValue }})

MongoDB Query - Filter only works with "_id"

I'm using mongodb v4.0.3, and this happens both with the shell and in compass.
This only happens with a certain collection. It previously had overriden ids (instead of the default mongodb id, there was a string. I dropped the collection and I recreated it without that).
I have the following structure ("mystructure"), for example:
{
"_id":ObjectId("5bd44eb528d61e3374b5e6ea"),
"custom_field":"data",
}
When I query it without a filter it returns all the docs:
db.mystructure.find({});
When I search for its objectid, it returns properly
db.mystructure.find( {"_id": ObjectId("5bd44eb528d61e3374b5e6ea")} );
But when I try to filter with any field, it doesn't return anything
db.mystructure.find( {"custom_field": "data"} );
At first I thought it would be solved recreating the collection with the automatically generated ids from mongodb but the problem persists. There are no "hidden" spaces in the string or anything like that. The same query in compass isn't working either. Other collections do work. It's on the same db, with the same user.
Why can this be?
Thank you very much.
you should write below code where 62c01e5a763d106152a2e53f is your _id
{_id:ObjectId('62c01e5a763d106152a2e53f')}

Some MongoDB questions

I'm new to MongoDB and Meteor. I have checked the official docs but seems they didn't do good job. Here I have couple of questions.
The structure is as follows.
{
_id:"127467812649871246",
"name":"Disha",
"last_name":"shukla",
"members":
[
{
name:"xyz"
},
{
name:"abc"
}
],
"user":"premium"
}
1] How to insert data in particular field when the data is already exists by referring the record ID ? In this case, insert a new member in "Members"
2] In some cases there wont be "user":"premium" field. Because I wont insert at first time. How do I check if that field is exists if I have inserted for some document ?
Any help will be appreciated :)
Thank you!
The $push command is used to insert data into an existing array in MongoDB. And $exists is used to check whether a field exists in a collection. Go to the links to find more.
1) You can use update by some selector, for example by name
CollectionName.update({name:"Disha"}, {$push: {members: {name: "new"}}})
2) If you want to check if the field exists use this
CollectionName.find({user: {$exists:true}}).
If you want to check if user is premium
CollectionName.find({user: "premium"}).
If you want to check both:
CollectionName.find({$and: [{user: {$exists:true}}, {user: "premium"}]})

Trouble updating last document from a query

Hello I'm new to Mongodb, I am currently trying to update the last document in a query result but having trouble doing so.
I know how to get the last document using
db.collection.find().sort({$natural:-1}).limit(1)
but how do I update this? I tried doing:
db.collection.update(db.collection.find().sort({$natural:-1}).limit(1))
But that didn't work. And I don't think:
db.collection.update(query,update,option).sort({$natural:-1}).limit(1))
would do what i want. I checked the official documentation but couldn't find anything on querying only for the last document.
You can use findAndModify to perform an update that requires sorting to identify the document to update:
db.test.findAndModify({
query: {},
sort: {$natural: -1},
update: {$set: {foo: 'bar'}}
})
You can also do it this way:
var id = db.collection.find().sort({$natural:-1}).limit(1)[0]['_id'];
db.collection.update({_id: id},{...})

Remove only one document in MongoDB

when I call
db.collection.remove({'condition':'some condition'});
This one line will delete all the matching condition documents.
What If I want to remove only one of any or n-th matching condition?
You need to perform two separate queries for this
take only one item from the matching filters
var item = db.collection.findOne({'condition':'some condition'})
and delete the item by using the id
db.collection.remove({_id: item._id});
db.collection.remove now has a justOne flag
http://docs.mongodb.org/manual/reference/method/db.collection.remove/#db.collection.remove
If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method.
Here, you want to delete only 1. Thus, set "justOne" parameter as 1.
db.collection.remove({'condition':'some condition'},1);
To remove one document from collection use the bellow command
db.collectionname.remove({"_id": ObjectId("5473293d43ecdre56352457f3a")})
According to MongoDB db.collection.remove() reference:
justOne
An optional boolean value. To limit the deletion to just one document, set to true. Omit to use the default value of false and delete all documents matching the deletion criteria.
You can set the justOne to true, in order to do it.
Before MongoDB version 2.6:
db.collection.remove(
<query>,
<justOne>
)
MongoDB version 2.6 or later:
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
Like this: db.collection.remove({"condition": "some condition"}, {justOne: true});.
I used this and it's worked for me
db.eventList.remove({"_id":ObjectId("5d9f3bd0c02cef7d50bb97fb")});
this is working on MongoDB shell version: 3.2.17
here eventList ===> collection
Can't you just run a find first to get the id then a delete when you have the one you want?
Try this one for delete.
db.users.deleteOne({"_id": ObjectId("5473293d43ecdre56352457f3a")});
For example the name of the db is 'abc' and under that there's a collection by name 'users' and users has an email which is 'test#test.com' which you want to remove:
1. On the terminal if you type 'show dbs' (without quotation' ') it would list all the databases including 'abc'
2. If you type 'use abc', it would switch to your desired db - abc (with the message: "switched to db abc")
3. Now if you type 'show collections', it would show all the collections including 'users'
4. If you want to list all the documents in this collection, you simply type: db.users.find({})
5. If you want to delete a specific document in this collection, type:
db.users.remove({"email":"test#test.com"})
If it's successful, it would display - WriteResult({ "nRemoved" : 1 })