Remove only one document in MongoDB - 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 })

Related

Update value in MongoDB

I have to add new value (or edit actual) company. I tried this code in console:
db.users.update({email: /debute/},{company: "test"})
But now, in database I have only _id and company. Why other values removed? Or how can I prevent of removing other values in future?
By default, the update function replaces the entire document with the document you pass. But you can also use it to only replace individual fields and leave the others alone by using the $set operator.
db.users.update({email: /debute/},{ $set: { company: "test"} } );
You might also want to specify a third argument { multi: true } to the update. Otherwise it will only update the first document it finds which matches the condition.
You need to use an update operator on order to update an existing document, your code replaces the document with the new document. Here is how to do an update:
db.users.update({email: /debute/},{$set: {company: "test"}})

update mongo db documents with regex

I need to find all the documents in mongodb that have keywords that start with number 1-9, then add a '+' in front of the keyword, I can easily find the documents but cannot figure out how to update them.
I tried this one, but it doesn't work
db.placements.update({program_id:{$in:[113,107]},
keyword:{$regex:'^[0-9]', $options:'i'}},
{keyword:"+"+$keyword})
It cannot recognize $keyword, I also tried '.keyword', 'keyword', none of them works. Is there any way to reference the document itself like Java does, using 'this', so I can do something like
this.keyword: "+" + this.keyword
You'll have to use the $set operator in the update query to update a specific field. Also, you cannot concatenate string within an update query. One way to do this would be using cursor forEach() in the shell:
db.placements.find({program_id:{$in:[113,107]}, keyword:{$regex:'^[0-9]', $options:'i'}})
.forEach(function(doc){
db.placements.updateOne({_id:doc._id}, {$set:{"keyword":"+" + doc.keyword}})
})
No, you cannot reference a value on the document itself when querying like you can with SQL.
I would suggest querying the document, updating it on your web/app server and then updating the value back to mongodb.
You will also find that your update command above will wipe your entire document leaving only the keyword field. You should use the $set modifier to update a field or set of fields.
db.placements.update(
{
program_id:{$in:[113,107]},
keyword:{$regex:'^[0-9]', $options:'i'}
},
{ $set: {keyword: new_value}})

Updating multiple documents in mongodb using _id field

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

Doing an upsert in mongo, can I specify a custom query for the "insert" case? [duplicate]

I am trying to use upsert in MongoDB to update a single field in a document if found OR insert a whole new document with lots of fields. The problem is that it appears to me that MongoDB either replaces every field or inserts a subset of fields in its upsert operation, i.e. it can not insert more fields than it actually wants to update.
What I want to do is the following:
I query for a single unique value
If a document already exists, only a timestamp value (lets call it 'lastseen') is updated to a new value
If a document does not exists, I will add it with a long list of different key/value pairs that should remain static for the remainder of its lifespan.
Lets illustrate:
This example would from my understanding update the 'lastseen' date if 'name' is found, but if 'name' is not found it would only insert 'name' + 'lastseen'.
db.somecollection.update({name: "some name"},{ $set: {"lastseen": "2012-12-28"}}, {upsert:true})
If I added more fields (key/value pairs) to the second argument and drop the $set, then every field would be replaced on update, but would have the desired effect on insert. Is there anything like $insert or similar to perform operations only when inserting?
So it seems to me that I can only get one of the following:
The correct update behavior, but would insert a document with only a subset of the desired fields if document does not exist
The correct insert behavior, but would then overwrite all existing fields if document already exists
Are my understanding correct? If so, is this possible to solve with a single operation?
MongoDB 2.4 has $setOnInsert
db.somecollection.update(
{name: "some name"},
{
$set: {
"lastseen": "2012-12-28"
},
$setOnInsert: {
"firstseen": <TIMESTAMP> # set on insert, not on update
}
},
{upsert:true}
)
There is a feature request for this ( https://jira.mongodb.org/browse/SERVER-340 ) which is resolved in 2.3. Odd releases are actually dev releases so this will be in the 2.4 stable.
So there is no real way in the current stable versions to do this yet. I am afraid the only method is to actually do 3 conditional queries atm: 1 to check the row, then a if to either insert or update.
I suppose if you had real problems with lock here you could do this function with sole JS but that's evil however it would lock this update to a single thread.

Mongodb upsert only update selected fields, but insert all

I am trying to use upsert in MongoDB to update a single field in a document if found OR insert a whole new document with lots of fields. The problem is that it appears to me that MongoDB either replaces every field or inserts a subset of fields in its upsert operation, i.e. it can not insert more fields than it actually wants to update.
What I want to do is the following:
I query for a single unique value
If a document already exists, only a timestamp value (lets call it 'lastseen') is updated to a new value
If a document does not exists, I will add it with a long list of different key/value pairs that should remain static for the remainder of its lifespan.
Lets illustrate:
This example would from my understanding update the 'lastseen' date if 'name' is found, but if 'name' is not found it would only insert 'name' + 'lastseen'.
db.somecollection.update({name: "some name"},{ $set: {"lastseen": "2012-12-28"}}, {upsert:true})
If I added more fields (key/value pairs) to the second argument and drop the $set, then every field would be replaced on update, but would have the desired effect on insert. Is there anything like $insert or similar to perform operations only when inserting?
So it seems to me that I can only get one of the following:
The correct update behavior, but would insert a document with only a subset of the desired fields if document does not exist
The correct insert behavior, but would then overwrite all existing fields if document already exists
Are my understanding correct? If so, is this possible to solve with a single operation?
MongoDB 2.4 has $setOnInsert
db.somecollection.update(
{name: "some name"},
{
$set: {
"lastseen": "2012-12-28"
},
$setOnInsert: {
"firstseen": <TIMESTAMP> # set on insert, not on update
}
},
{upsert:true}
)
There is a feature request for this ( https://jira.mongodb.org/browse/SERVER-340 ) which is resolved in 2.3. Odd releases are actually dev releases so this will be in the 2.4 stable.
So there is no real way in the current stable versions to do this yet. I am afraid the only method is to actually do 3 conditional queries atm: 1 to check the row, then a if to either insert or update.
I suppose if you had real problems with lock here you could do this function with sole JS but that's evil however it would lock this update to a single thread.