I just started learning mongoDB and I noticed a collection which is removed by .remove() command still exist after the executing.
am I doing something wrong or this is how it's supposed to work?
by using mongo
use testDB
db.stats() // returns "db" : "testDB","collections" : 0,"objects" : 0
//and db.getCollectionNames() returns nothing as well
db.testCollection.insert({ test : 'abc'})
db.getCollectionNames() // [ "system.indexes", "testCollection" ]
db.testCollection.remove()
db.testCollection.find() // returns nothing
db.getCollectionNames() // [ "system.indexes", "testCollection" ]
db.stats() // "db" : "testDB","collections" : 3,"objects" : 4
You missed the point of remove operation in mongodb. It does not remove the collection, it removes all documents in the collection which specify the query. If you do remove() you specify nothing in your query, thus it removes everything.
To remove collection do db.collection.drop()
Related
I’m using upsert with the updateOne() method as bellow to perform an update.
db.practice.updateOne(
{“title”:“Night Life”},
{$set: detail},
{upsert: true}
)
My query returns the following:
{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : ObjectId("5f8884fed29ded706c3c6737")
}
Below is the detail variable:
let detail = {
“title” : “Night Life”,
“year” : 2021,
“rated” : “PG-13”,
“released” : 2021,
“runtime” : 60,
“countries” : [
“USA”,
“UK”
],
“genres” : [
“comedy”,
“drama”
],
“director” : “Alpha Ly”,
“actors” : [
“Alpha Ly”,
“Kris Dasha”,
“Hope Grace”
]
}
When I check my collection in Compass, I don’t see the document with the ObjectId("5f8884fed29ded706c3c6737
However, when I run the following command db.practice.find({"director": "Alpha Ly"}).pretty(),
it returns the entry I've looking for in Compass.
NB: the number of documents in my collection is still the same as created.
What seems to be the problem here. Why Compass is not displaying the entry?
It seems like I was not using the correct database.
In order to execute the command, I was supposed to use the use command followed by the name of my database to switch to my database. Since I didn't, the update query created another collection and inserted the document there. Therefore, I couldn't find it in my database.
Thanks
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() 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.
So I have following structure of MongoDB collection
{ "_id" : ObjectId("516c48631f6c263a24fbbe7a"), "oldname" : 1, "name" : "somename" }
and I want to rename OLD NAME to NEW NAME so it will look like,
{ "_id" : ObjectId("516c48631f6c263a24fbbe7a"), "newname" : 1, "name" : "somename" }
so I am writing this command,
db.element_type.update({}, {$rename: {'oldname': 'newname'}}, false, true);
But it is giving me this error
failing update: objects in a capped ns cannot grow
The problem, per the error message, is that you're trying to update a capped collection, presumably with a newname that is longer than the oldname.
You can read about capped collections in the docs. They're designed to maintain their order, which is why you're running into this.
If you must use a capped collection, perhaps you should remove and re-insert instead of updating.
I can't figure out how to remove documents that I created while testing my app. From within the mongo shell I get this:
> db.carshare.remove();
> show dbs
carshare 0.203125GB
crushFlow 0.203125GB
local (empty)
test (empty)
> db.carshare.remove({});
> show dbs
carshare 0.203125GB
crushFlow 0.203125GB
local (empty)
test (empty)
I'm a beginner and must be missing something very obvious, help?
MongoDB has a hierarchy structure that is DB -> collection -> documents.
So, are you trying to remove a DB, a collection, or a document?
Assuming a DB 'foo', with a collection 'test', with two documents:
> db.test.find();
{ "_id" : ObjectId("4ef54ed6c143a725c52d7ff6"), "name" : "mongo" }
{ "_id" : ObjectId("4ef54eeec143a725c52d7ff7"), "name" : "bob" }
to remove a document:
> db.test.remove({'name':'bob'});
> db.test.find();
{ "_id" : ObjectId("4ef54ed6c143a725c52d7ff6"), "name" : "mongo" }
to remove a collection:
> db.test.drop();
true
> show collections;
system.indexes
to remove a DB:
db.dropDatabase();
{ "dropped" : "foo", "ok" : 1 }
The Mongo documentation is very good:
http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell#Overview-TheMongoDBInteractiveShell-Deleting
http://www.mongodb.org/display/DOCS/dbshell+Reference
"carshare" and "crushFlow" are the names of databases (which is the output you get from showdb). If you want to see collections to remove documents from type use dbname (test by default) and then type show collections.
The list of collections that appears can have their documents removed by doing db.collection.remove() where collection is the collection name and db is now set to the database you want via the use databasename command.
Good luck and cheers!