I want to insert one document into collection1 and after successfully inserting the document, I want to insert another document into collection2. One of the fields for the document in collection2 will be the _id of the document just inserted into collection1.
I am using a callback:
db.collection1.insert(<document>,function(err,doc)){
db.collection2.insert({collection1_id: doc[0]._id, <field>:<value>})
However, it seems that callback is not available without Node.js.
Is there any workaround?
Callbacks are part of the Node.js async API and are not supported in the mongo shell (as at MongoDB 4.0). However, you can always write the equivalent without callbacks.
The mongo shell's insertOne() method will return an insertedId field with the _id value of the inserted document, so you can either save or reference this value.
For example:
db.collection2.insertOne({
collection1_id: db.collection1.insertOne({}).insertedId,
field: 'value'
})
Related
I am using python and mongoengine for this project.
And i am creating a restAPI. Since save() query in mongo inserts new or updates existing document.
SearchRating(stars=4, comment='').save() // returns "None" on success
This particular piece of code in mongoengine only creates new document. However the idea is that only once user is suppose to create this document, later they should only update it. But for updation i need to know what _id i just added in mongodb in search_rating collection.
So how shall i know the _id of document that i just added?
We are using MongoDB framework in C# for DB calls.
When we insert new document in collection, we want updated result with inserted _id into database.
After you insert document using official C# driver, you already have it with updated _id column. Inserted document is updated by default.
While reading about Mongo Save and Update ,I got bit confuse -as per article
MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.
Please let me know difference in both .
update changes an existing document found by your find-parameters and does nothing when no such document exist (unless you use the upsert option).
save doesn't allow any find-parameters. It checks if there is a document with the same _id as the one you save exists. When it exists, it replaces it. When no such document exists, it inserts the document as a new one. When the document you insert has no _id field, it generates one with a newly created ObjectId before inserting.
collection.save(document); is basically a shorthand for:
if (document._id == undefined) {
document._id = new ObjectId();
}
collection.update({ "_id":document._id }, document, { upsert:true });
From the documentation:
Save command.
The save() method uses either the insert or the update command, which
use the default write concern. To specify a different write concern,
include the write concern in the options parameter.
If the document does not contain an _id field, then the save() method
calls the insert() method.
If the document contains an _id field, then the save() method is
equivalent to an update with the upsert option set to true and the
query predicate on the _id field.
Update command
if upsert is not specified it
Modifies an existing document or documents in a collection. The method
can modify specific fields of an existing document or documents or
replace an existing document entirely, depending on the update
parameter.
If upsert is true and no document matches the query criteria, update()
inserts a single document.
So they are pretty similar and both can update and insert the document. The difference is that save can update only one document.
While writing data to mongodb, we are checking if the data is present get the _id and using save update it else using insert add the data. Read save is the best way if you are providing _id in the query while saving it will update/insert based on if the _id is present in the db. Is the save the best method or is there any other way.
If you have all data available to save, just run update() each time but use the upsert functionality. Only one query required:
db.collection.update(
['_id' => $id],
$data,
['upsert' => true]
);
If your _id is generated by mongo you always know there is a record in the database and update is the one to use, but then again you could also save().
If you generated your id's (and thus don't know if it comes from the collection), this will always work without having to run an extra query.
From the documentation
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
db.collection.insert()
Inserts a document or documents into a collection.
If you use db.collection.insert() in your case you will get duplication key error since it will try to insert new document which has same _id with an existing document. But instead of using save you should use the update method.
I know this may be a silly question, but I read on an e-book that there is an upsert option in MongoDB insert. I couldn't find proper documentation about this. Can someone educate me about this?
Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upsertsin insert command. It is an option for the update command. If you execute command like below it works as an update, if there is a document matching query, or as an insert with document described by update as an argument.
db.collection.update(query, update, {upsert: true})
MongoDB 3.2 adds replaceOne:
db.collection.replaceOne(query, replacement, {upsert: true})
which has similar behavior, but its replacement cannot contain update operators.
As in the links provided by PKD, db.collection.insert() provides no upsert possibility. Instead, mongo insert inserts a new document into a collection. Upsert is only possible using db.collection.update() and db.collection.save().
If you happen to pass a document to db.collection.insert() which is already in the collection and thus has an _id similar to an existing _id, it will throw a duplicate key exception.
For upserting a singe document using the java driver:
FindOneAndReplaceOptions replaceOptions = new FindOneAndReplaceOptions();
replaceOptions.upsert(true);
collection.findOneAndReplace(
Filters.eq("key", "value"),
document,
replaceOptions
);
Although uniqueness should be ensured from Filters.eq("key", "value") otherwise there is a possibility of adding multiple documents. See this for more