remove needs a query at src/mongo/shell/collection.js - mongodb

Getting this error when I run db.messages.remove(). "remove needs a query at src/mongo/shell/collection.js". any suggestions to resolve this error?

As the message says you need to provide a query, but it can be an empty one (if you want to remove all documents):
db.messages.remove({})
EDIT: I would like emphasize the comment made by Stennie:
Note: if you actually want to remove all documents in a collection it is faster to a do a collection.drop(). The remove() operation will delete documents individually & update indexes as the documents are deleted; a drop() will immediately delete all documents & indexes for the collection.

If you are trying to drop the collection messages, then you need to execute db.messages.drop().
Otherwise, the command db.messages.remove() is used to delete a particular document and therefore you need to write a query to allow MongoDB engine to know which document needs to be gotten rid of. For ex. db.messages.remove({_id : }).
The lack of {_id : } is causing the error that remove needs a query....

Run:
db.collectionname.remove({});
result :
WriteResult({ "nRemoved" : 7 })

Remove all collections from MongoDB database, use below Syntax:
db.getCollectionNames().forEach(
function(collection_name){
print('CollectionName: '+ collection_name +', '+ db[collection_name].remove({})
)
});
Output:
CollectionName: Document_CODE, WriteResult({ "nRemoved" : 20 })
CollectionName: Document_DATA, WriteResult({ "nRemoved" : 10 })
CollectionName: Document_NAME, WriteResult({ "nRemoved" : 10 })
CollectionName: Document_COLLE, WriteResult({ "nRemoved" : 1 })

Related

pymongo update creates a new record without upserting

I have an issue where I do an update on a document, however, the update creates a new document and I'm not upserting in my update.
This is my testing code.
I do a find to see if the document exists by checking if "lastseen" doesn't exist:
result = DATA_Collection.find({"sessionID":"12345","lastseen":{"$exists":False}})
if result.count() == 1:
DATA_Collection.update({"sessionID":"12345"},{"$set":{"lastseen":"2021-05-07"}})
When I do an aggregate check to find duplicates I get a few, one example below.
> db.DATA_Collection.find({ "sessionID" : "237a5fb8" })
{ "_id" : ObjectId("60bdf7b05c961b4d27d33bde"), "sessionID" : "237a5fb8", "firstseen" : ISODate("1970-01-19T20:51:09Z"), "lastseen" : ISODate("2021-06-07T12:34:20Z") }
{ "_id" : ObjectId("60bdf7fa7d35ea0f046a2514"), "sessionID" : "237a5fb8", "firstseen" : ISODate("1970-01-19T20:51:09Z") }
I remove all the records in the collection and rerun the script, the same happens again.
Any advice will be much appreciated.
Firstly your pymongo commands are deprecated; use update_one() or update_many() instead of update(); count_documents() instead of count().
Secondly double check you are referencing the same collections as you mention DATA_Collection and VPN_DATA;
How are you defining a "duplicate"? Unless you create a unique index on the field(s), the records won't be duplicates as they have different _id fields.
You need something like:
record = db.VPN_DATA.find_one({'sessionID': '12345', 'lastseen': {'$exists': False}})
if record is not None:
db.VPN_DATA.update_one({'_id': record.get('_id')}, {'$set': {'lastseen': '2021-05-07'}})

How to find out what is being modified by an Update query in mongodb?

I have a collection of users with 3 fields, UserID, State, and IsLocked.
I'm going to update all users State to 3 and IsLocked to true, Before issuing the update query I ran the following two queries:
> db.Users.find({isLocked:{$ne:true}})
> db.Users.find({State:{$ne:3}})
They both return nothing, so I assume all users have their isLocked set to true and their State are set to 3.
After that I ran the update query:
> db.Users.update({},{$set:{State:3,isLocked:true}},{ multi: true })
WriteResult({ "nMatched" : 43206, "nUpserted" : 0, "nModified" : 3 })
I'm very confused about the number of nModified.
I expect it to be 0 because all documents already have their State set to 3 and isLocked to true.
Is there something I'm missing here?
You only get counts in case of updates affecting multiple documents i.e multi:true. For single document update you can use findOneAndUpdate with returnNewDocument:true to return the updated document.
So it looks like you've documents where either State or isLocked fields are missing.
For example
Try
db.Users.find({isLocked:{$exists:false}})
db.Users.find({State:{$exists:false}})
which should return 3 documents.
Include the check to only update fields where isLocked and state both are present.
db.Users.update({isLocked:{$exists:true}, State:{$exists:true}},{$set:{State:3,isLocked:true}},{ multi: true })
Include the check to only update fields where isLocked or state is present.
db.Users.update({$or:[{isLocked:{$exists:true}}, {State:{$exists:true}}]},{$set:{State:3,isLocked:true}},{ multi: true })

Can not create empty collection in MongoDB using Meteor

I have the next code in lib/ folder
TestCollection = new Mongo.Collection('testCollection');
I expect that this code should create empty collection in MongoDB,but it doesn't.
This collection is created only when I insert some data.
TestCollection = new Mongo.Collection('testCollection');
TestCollection .insert({ foo: 'blah', bar: 'bleh' });
I want to create an empty collection without simultaneously inserting data. Is it possible?
I looked at similar posts,but they insert data immediately after the creation collection. I want first create collection and much later insert data.
From Meteor, no. You can create an empty collection from the mongo shell using db.createCollection
Otherwise just insert a doc and remove it right away as suggested by #CodeChimp
same as Michel Floyd say, I have done this in mongodb shell:
> use storybook
> db.main.insert({"fakeKey": "fakeValue"})
WriteResult({ "nInserted" : 1 })
> db.main.find()
{ "_id" : ObjectId("5bd2bddb6ec5fdeabfbd6ecb"), "fakeKey" : "fakeValue" }
> db.main.deleteOne({"_id": ObjectId("5bd2bddb6ec5fdeabfbd6ecb")})
{ "acknowledged" : true, "deletedCount" : 1 }
then via:
db.main.find()
you can find that already added an empty db's collection.

What's the difference between insert(), insertOne(), and insertMany() method?

What's the difference between insert(), insertOne(), and insertMany() methods on MongoDB. In what situation should I use each one?
I read the docs, but it's not clear when use each one.
What's the difference between insert(), insertOne() and insertMany() methods on MongoDB
db.collection.insert() as mentioned in the documentation inserts a document or documents into a collection and returns
a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts.
> var d = db.collection.insert({"b": 3})
> d
WriteResult({ "nInserted" : 1 })
> var d2 = db.collection.insert([{"b": 3}, {'c': 4}])
> d2
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
db.collection.insertOne() as mentioned in the documentation inserts a document into a collection and returns a document which look like this:
> var document = db.collection.insertOne({"a": 3})
> document
{
"acknowledged" : true,
"insertedId" : ObjectId("571a218011a82a1d94c02333")
}
db.collection.insertMany() inserts multiple documents into a collection and returns a document that looks like this:
> var res = db.collection.insertMany([{"b": 3}, {'c': 4}])
> res
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("571a22a911a82a1d94c02337"),
ObjectId("571a22a911a82a1d94c02338")
]
}
In what situation should I use each one?
The insert() method is deprecated in major driver so you should use the
the .insertOne() method whenever you want to insert a single document into your collection and the .insertMany when you want to insert multiple documents into your collection. Of course this is not mentioned in the documentation but the fact is that nobody really writes an application in the shell. The same thing applies to updateOne, updateMany, deleteOne, deleteMany, findOneAndDelete, findOneAndUpdate and findOneAndReplace. See Write Operations Overview.
db.collection.insert():
It allows you to insert One or more documents in the collection. Syntax:
Single insert: db.collection.insert({<document>});
Multiple insert:
db.collection.insert([
, , ...
]);
Returns a WriteResult object: WriteResult({ "nInserted" : 1 });
db.collection.insertOne():
It allows you to insert exactly 1 document in the collection. Its syntax is the same as that of single insert in insert().
Returns the following document:
{
"acknowledged" : true,
"insertedId" : ObjectId("56fc40f9d735c28df206d078")
}
db.collection.insertMany():
It allows you to insert an array of documents in the collection. Syntax:
db.collection.insertMany(
{ [ <document 1> , <document 2>, ... ] });
Returns the following document:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("562a94d381cb9f1cd6eb0e1a"),
ObjectId("562a94d381cb9f1cd6eb0e1b"),
ObjectId("562a94d381cb9f1cd6eb0e1c")
]
}
All three of these also allow you to define a custom writeConcern and also create a collection if it doesn't exist.
There is also a difference in error handling, check here. The insert command returns a document in both success and error cases. But the insertOne and insertMany commands throws exceptions. Exceptions are easier to handle in code, than evaluating the returned document to figure out errors. Probably the reason why they are deprecated in the drivers as mentioned in sstyvane's answer.
Also to add to another answer, if the user calls the InsertOne function instead of InsertMany and passes the array of documents to insert. then it is also allowed and will not give any errors. It will create only one document which will have an array of these documents. so be careful.
If the collection does not exist, then the insertOne() method creates the collection. If you input the same data again, mongod will create another unique id to avoid duplication.

WriteResult mongoDB for update operation

I want to insert records and updating attributes using update and get the status of the update. I used getN () method WriteResult. The problem is that if the attributes exist it always returns me one while I wish that I returns 0. thank you
here is my update request :
db.friends.update( {adv: "man2ist", "list.id" : {$ne : "5" }} , {$addToSet : {"list" : {'id' : "5" , 'value' : 100 }} } ,false , true);
The n value in a WriteResult provides the number of documents that were updated, and it can only be 0 if your update query didn't match any documents and you're not doing an upsert. Your best bet here might be to use findAndModify and make a comparison to the old document.