Can not create empty collection in MongoDB using Meteor - mongodb

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.

Related

MongoDB insert data after find query

I'm using MongoDB with Mongochef GUI over an Ubuntu Virtual Machine. I need to do a Query which insert the data that I have found previously.
How can i do this? I thought something like this:
db.createCollection("prueba", { capped : true, size : 5242880, max : 5000 } )
db.gmap.find( { emotion: 1 } )
db.prueba.insertMany(db.gmap.find( { emotion: 1 } ))
GMAP is other collection that i have and the find query returns needed data.
Thanks
To solve that we need to store result as an array and then insert - please find snippet below:
var a = db.sourceCollection.find().toArray()
db.destinatioCollection.insert(a)
To exclude some fields use the find projection option: in this example the "_id" field is excluded, usefull to insert in the same collection.
To insert many documents use insertMany method:
db.dstColl.insertMany( db.srcColl.find({}, {"_id": false}).toArray() )

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.

How to remove _id from MongoDB results?

I am inserting json file into Mongodb(with Scala/Play framework) and the same getting/downloading it into my view page for some other requirement, but this time it is coming with one "_id" parameter in the json file.
But I need only my actual json file only that is not having any any "_id" parameter. I have read the Mongodb tutorial, that by default storing it with one _id for any collection document.
Please let me know that how can I get or is there any chance to get my actual json file without any _id in MongoDB.
this is the json result which is storing in database(I don't need that "_id" parameter)
{
"testjson": [{
"key01": "value1",
"key02": "value02",
"key03": "value03"
}],
"_id": 1
}
If you have a look at ReactiveMongo dev guide and to its API, you can see it support projection in a similar way as the MongoDB shell.
Then you can understand that you can do
collection.find(selector = BSONDocument(), projection = BSONDocument("_id" -> 0))
Or, as you are using JSON serialization:
collection.find(selector = Json.obj(), projection = Json.obj("_id" -> 0))
You can use this query in the shell:
db.testtable.find({},{"_id" : false})
Here we are telling mongoDB not to return _id from the collection.
You can also use 0 instead of false, like this:
db.testtable.find({},{"_id" : 0})
for scala you need to convert it in as per the driver syntax.

MongoDB: If document exists VS If document does not exist

I'm a beginner at MongoDB and I'm currently pairing it with php to try to make the following work:
I want to create a database to store information that can get updated at any time but it needs to keep a "document added on:" date.
In sum:
IF document exists:
-Update everything in the document except the "document added on" date entry.
ELSE
-Create a document with the data + a "document added on: XXXXX" date.
In a case of a database with this format:
Database{ document{ User_ID: "12345", Name: "Joe", More_Info: "" Date_Added_To_DB: "1372291496", Last_Updated:"1372291556"}}
I've researched and asked around and the best I've got so far is a function that will update a whole document if it exists and create a new document if it does not.
db.Database.update({'User_ID' : $userID},{$set: {'fieldName' : new "data" }}, {upsert: true})
The question is how you determine that "the document" exists? Usually, you'd do this using a unique id. Now MongoDB's ObjectId comes to the rescue because it contains a timestamp already. This can also be used in queries.
Instead of using an integer field User_ID, you might want to consider calling the field _id and use the ObjectId data type so you get that functionality for free.
> db.test.insert({"foo" : "test"});
{ "_id" : ObjectId("51cb763e58bb4077aea65b3d"), "foo" : "test" }
> var foo = db.test.findOne();
> foo._id.getTimestamp();
ISODate("2013-06-26T23:16:14Z")

Get position of selected document in collection [mongoDB]

How to get position (index) of selected document in mongo collection?
E.g.
this document: db.myCollection.find({"id":12345})
has index 3 in myCollection
myCollection:
id: 12340, name: 'G'
id: 12343, name: 'V'
id: 12345, name: 'A'
id: 12348, name: 'N'
If your requirement is to find the position of the document irrespective of any order, that is not
possible as MongoDb does not store the documents in specific order.
However,if you want to know the index based on some field, say _id , you can use this method.
If you are strictly following auto increments in your _id field. You can count all the documents
that have value less than that _id, say n , then n + 1 would be index of the document based on _id.
n = db.myCollection.find({"id": { "$lt" : 12345}}).count() ;
This would also be valid if documents are deleted from the collection.
As far as I know, there is no single command to do this, and this is impossible in general case (see Derick's answer). However, using count() for a query done on an ordered id value field seems to work. Warning: this assumes that there is a reliably ordered field, which is difficult to achieve in a concurrent writer case. In this example _id is used, however this will only work with a single writer case.:
MongoDB shell version: 2.0.1
connecting to: test
> use so_test
switched to db so_test
> db.example.insert({name: 'A'})
> db.example.insert({name: 'B'})
> db.example.insert({name: 'C'})
> db.example.insert({name: 'D'})
> db.example.insert({name: 'E'})
> db.example.insert({name: 'F'})
> db.example.find()
{ "_id" : ObjectId("4fc5f040fb359c680edf1a7b"), "name" : "A" }
{ "_id" : ObjectId("4fc5f046fb359c680edf1a7c"), "name" : "B" }
{ "_id" : ObjectId("4fc5f04afb359c680edf1a7d"), "name" : "C" }
{ "_id" : ObjectId("4fc5f04dfb359c680edf1a7e"), "name" : "D" }
{ "_id" : ObjectId("4fc5f050fb359c680edf1a7f"), "name" : "E" }
{ "_id" : ObjectId("4fc5f053fb359c680edf1a80"), "name" : "F" }
> db.example.find({_id: ObjectId("4fc5f050fb359c680edf1a7f")})
{ "_id" : ObjectId("4fc5f050fb359c680edf1a7f"), "name" : "E" }
> db.example.find({_id: {$lte: ObjectId("4fc5f050fb359c680edf1a7f")}}).count()
5
>
This should also be fairly fast if the queried field is indexed. The example is in mongo shell, but count() should be available in all driver libs as well.
This might be very slow but straightforward method. Here you can pass as usual query. Just I am looping all the documents and checking if condition to match the record. Here I am checking with _id field. You can use any other single field or multiple fields to check it.
var docIndex = 0;
db.url_list.find({},{"_id":1}).forEach(function(doc){
docIndex++;
if("5801ed58a8242ba30e8b46fa"==doc["_id"]){
print('document position is...' + docIndex);
return false;
}
});
There is no way that MongoDB can return this as it does not keep documents in order in the database, just like MySQL f.e. doesn't name row numbers.
The ObjectID trick from jhonkola will only work if only one client creates new elements, as the ObjectIDs are generated on the client side, with the first part being a timestamp. There is no guaranteed order if different clients talk to the same server. Still, I would not rely on this.
I also don't quite understand what you are trying to do though, so perhaps mention that in your question? I can then update the answer.
Restructure your collection to include the position of any entry i.e {'id': 12340, 'name': 'G', 'position': 1} then when searching the database collection(myCollection) using the desired position as a query
The queries I use that return the entire collection all use sort to get a reproducible order, find.sort.forEach works with the script above to get the correct index.