Data insertion in MongoDB
We will continue with our Collection User for data insertion. Let us consider various scenarios for inserting data in Collection User.
- Suppose, we want to create a document in Collection User with fields name and description, we will make use of following code snippetIn, the above code snippet, we used getCollection() method in order to get the existing Collection User. An object of BasicDBObject is created and fields (“name” and “description”) are appended with values. Output generated can be found by using MongoDB Compass.
The output for our Query is XYZ against field name. Data insertion in MongoDB against filed description.
- While creating document in Collection MongoDB provides its own unique id referred by field_id. If we want to provide our own custom id, we can provide it. Refer the below code snippet for the same.The above query output is :In the output, we can find that document is created with our unique custom id: _id:”xyz123”.
No comments:
Post a Comment