mongo-go-driver get inserted document - mongodb

Collection.InsertOne() returns a *InsertOneResult, which only contains the ID of the inserted document. To get the inserted document, you have to perform another Collection.Find() query. Is there a way to do this in a single step?
A current work around is to use Collection.FindOneAndUpdate() with Upsert set to true, as this returns a *SingleResult that can then be decoded into a struct, and sent back to the client.

If you wish your application to have the complete document:
Generate the _id on client side
Insert the complete document
At that point the document you have is exactly the document that the database has, and returning it from the insert is pointless.
Some other databases generate ids on the server side, but in case of MongoDB each driver implements id generation on the client side such that each document can be completely known prior to the insert.

Related

Mongoose how to stop using _id (don't store it) and use id instead

Since I will be listing my full database on /bots, and I want to use id instead of _id (discord uses id for everything, so I'm accustomed with id and not _id)
I don't even want to save id as _id in the database. So any idea what to do?
This is not possible!
MongoDB automatically creates an _id for every document that gets inserted into a database.
This is there in order to give you a one-to-one value that you will be able to use to identify each document.
The id also contains a timestamp to when you inserted the document which then can be used to optimize queries using indexes.
This is also a best practice to send the _id to the user (even if it's mapped to an id field) to then be able to query more efficiently and also to not expose their Discord Id to everyone.
Hope I could answer your question.
You could read more about it here:
https://docs.mongodb.com/manual/core/document/#the-id-field
How to remove _id in MongoDB and replace with another field as a Primary Key?

Can mongo document ID format be customised?

I would like to encode some meaning behinds first N characters of every document ID i.e. make first three characters determine a document type sensible to the system being used in.
You can have a custom _id when you insert the document. If the document to be inserted doesn't contain _id, then MongoDB will insert a ObejctId for you.
The _id can be of any type but keeping it uniform for all the documents makes sense if you are accessing from application layer.
You can refer one of the old questions at SO - How to generate unique object id in mongodb

create unique id in mongodb from last inserted id using pymongo

Is there a way I can find the last inserted document and the field, i.e. _id or id such that I can increment and use when inserting a new document?
The issue is that I create my own id count, but I do not store this, now I've deleted records, I cannot seem to add new records because I am attempting to use the same id.
There is no way to check insertion order in MongoDB, because the database does not keep any metadata in the collections regading the documents.
If your _id field is generated server-side then you need to have a very good algorithm for this value in order to provide collision avoidance and uniqueness while at the same time following any sequential constraints that you might have.

How to insert new document only if it doesn't already exist in MongoDB

I have a collection of users with the following schema:
{
_id:ObjectId("123...."),
name:"user_name",
field1:"field1 value",
field2:"field2 value",
etc...
}
The users are looked up by the user.name, which must be unique. When a new user is added, I first perform a search and if no such user is found, I add the new user document to the collection. The operations of searching for the user and adding a new user, if not found, are not atomic, so it's possible, when multiple application servers are connect to the DB server, for two add_user requests to be received at the same time with the same user name, resulting in no such user being found for both add_user requests, which in turn results with two documents having the same "user.name". In fact this happened (due to a bug on the client) with just a single app server running NodeJS and using Async library.
I was thinking of using findAndModify, but that doesn't work, since I'm not simply updating a field (that exists or doesn't exist) of a document that already exists and can use upsert, but want to insert a new document only if the search criteria fails. I can't make the query to be not equal to "user.name", since it will find other users.
First of all, you should maintain a unique index on the name field of the users collection. This can be specified in the schema if you are using Mongoose or by using the statement:
collection.ensureIndex('name', {unique: true}, callback);
This will make sure that the name field remains unique and will solve the problem of concurrent requests as you have specified in your question. You do not require searching when this index is set.

Which is the best way to insert data in mongodb

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.