How can i change _id field in MongoDB Collection to User_id? - mongodb

I am new user for MongoDB Database. In MongoDb whatever insert into some collection defaultly one field is added that is _id field.
For Example:
db.users.insert({"User_id":"1","User_Name":"xxx","Address":"yyyy"})
db.users.find()
It shows
{ "_id" : ObjectId("528475fc326b403f580d2eba"), "User_id" : "1", "User_Name" : "xxx",Address" : "yyyy" }
I don't need _id field and i want to replace that _id field to User_id with auto increment values.
Is it possible. Please help me. Thanks in advance.

_id field is really special in mongodb. This is your primary key there and there is no way you can have a document without it. Even if you are trying to insert the document without it, mongo will create it for you (as in your example). Moreover, you can not even modify _id field for you collection.
But you can create a document with your own _id. So if you want you can do db.users.insert({"_id":"1","User_Name":"xxx","Address":"yyyy"}) \\why exactly 1 is a string?
and remember that _id means user_id and also keep in mind that this _id should be unique
Keep in mind that mongodb is not like sql. It does not have autoincrement keys (by this I mean that it is not that creators did not know how to do it, but just that you can leave pretty much without it), but you can achieve create something that would resemble the same behaviour.

As for as I can understand your problem is that you want to use your mongoDB internal _id as your custom attribute. For example suppose the db contain the user Identity and having attributes like "_id , name , address ..." and you want to use this _id's value in your application as userId for external reference.
So as #SalvadorDali said _id field is really important in the mongoDB and you can not have a document without it. All you can do is let the db store the value by it's default _id but you can access outside using your own User_id by applying these two changes in your json file.
"properties": {
"userId":{
"type": "string",
"id":"true",
"index":"true",
"description": "unique id of identity"
}
}
now you store any unique value, it is stored in the db using default _id and outside you can have that value in userId field.
Correct me if i got your question wrong.

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?

Put a prefix for ObjectID for MongoDB _id field

I'm trying to put a prefix before the auto generated _id, to identify from which collection came an id, but I still want to use the mongo unique id generator.
So I can know that this id model_5e1a51821c9d44000089e3e0 came from the Model collection.
Is there a solution for that without messing with random string ?
Edit
The _id need to be string castable, since I use it as id in a graphQL object. I need to differentiate ids because I use an union in my schema and resolver need to know in which table to find the data.
The _id can be generated within an application with the constructor ObjectId(). If you want to add a prefix for the generated field, you can use an embedded document as a field for the _id, like this:
_id: {
idPrefix: "Model",
_id: ObjectId("5e1bd112b7f18a490a4bafb5")
}
Other way of identifying if a document is from another collection is use a separate boolean field:
{
_id: ObjectId("5e1bd112b7f18a490a4bafb5"),
isFromModel: <boolean true or false>,
...
}
There are some options available to do this, I'm just trying to tell you the way how would I do if I need this.
Step 1: You can generate the document and it will return you ObjectId (_id) .
Step 2: Take that value and prefix it with model like this.
let _id=5e1a51821c9d44000089e3e0;let new_idValue="model_"+_id;
Step3: Now update your document by _id and push new value in place of if as
this.db.document.findByIdAndUpdate(_id,{$set:{{_id:new_idValue}})
This is what you can do. If you find some best solution than mine, let me know as well. I will highly appreciate.

How to remove _id in MongoDB and replace with another field as a Primary Key?

I'm have a huge documents in a collection. I want to remove auto generated Object Id (_id key) from all the documents and replace it with another field as a Primary key?
I don't understand is why is there a need for a default Object Id in first place?
In mongodb each document must be unique, so you need an unique field to be used as id. If you do not provide one, mongodb will provide one for you automatically. However, if you want to give custom ids for whichever reason (improve query performance being one of them), you can do it manually. Here goes my suggestions:
If you are inserting a new document, you can manually set the _id field like:
doc._id = "12312312" //(Or whichever function to generate id you have)
doc.save(...)
But when you already have a document in the database, you cannot modify it anymore. What you can do is to make a copy of the document, save a new document with the same data and erase the old one:
// Fetch the documents
docs = db.clients.find({})
docs.forEach((doc) => {
//For each field you copy the values
new_doc.field = doc.field
new_doc._id = //YOUR ID FUNCTION
// insert the document, using the new _id
db.clients.insert(new_doc)
// remove the document with the old _id
db.clients.remove({_id: doc._id})
}
This question is similar to the following one:
How update the _id of one MongoDB Document?
Hope my answer was helpful
It is not possible to remove the _id field.
From https://docs.mongodb.com/manual/core/document/#the-id-field:
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
What you can do is name your primary key as _id.

Why is there an underscore in front of the MongoDb document id?

Why is there an underscore in front of the MongoDb document id ?
Why not call it "id" instead of "_id" ?
Is this part of a naming convention I'm not aware of ?
You may notice that MongoDB has a lot of functions (in the shell) and fields that start with an understore as a designation that they are internal or special and not user provided.
If you have your own "ID" then you can store it as "id" and still use the provided-by-MongoDB _id field although you are not required to use the ObjectId that MongoDB generates - you could store your own natural primary key in the "_id" field which will have a unique index on it always.

MongoDB - Create object with reference manually - DBRef doesn't work

for testing purposes I need to create manually some objects in a MongoDB. My Class has a reference field to another class. The referred object already exists.
I tried to put the Mongo-ID of my existing object as a value in my new object but I get the following error:
A ReferenceField only accepts DBRef: ['attribute'])
Now my question: Where do I get or find this DBRef?
An example:
I have a user in my db. I want to create a group which has the existing user as "creator". When I put the user-ID into the creator-field I get the error...
Edit:
I just found this link MongoDB - DBRef but the solution does not work for me...
item : {"$ref" : "fruit", "$id" : "1"}
My code is like this:
{ "name" : "MyGroup", "created_at" : "2011-05-22T00:46:38", "creator": { "$ref": "user", "$id": "501bd5ac32f28a1278e54435" } }
Another edit:
Even the Mongo doc says I'm using the right format... http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON. But still not working.
In the question you referenced, the user is using a numeric string as their document ID. In your case, it looks like you're working with the more-common ObjectId but inserting it as a string. Assuming you're using PyMongo, you probably want to use the ObjectId class for the $id property of the DBRef.
If you know all such references are going to point to the same DB and collection, it may make sense to use manual references (just storing the target document's _id) instead of DBRef objects. This is explained in more detail in the Database References documentation.