Inserting Documents in MongoDB
- Inserting a single document in the collection.
test> use students;
switched to db students
students> db.data.insertOne({'name': 'Prabin', age: 22});
{
acknowledged: true,
insertedId: ObjectId("64fabf5c7d6e92e1e0d959f7")
}
- Inserting multiple documents in the collection
students> db.data.insertMany([{'name': 'Ashok', age:23 }, {'name': 'Shubham', age: 24}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64fabff57d6e92e1e0d959f8"),
'1': ObjectId("64fabff57d6e92e1e0d959f9")
}
}
- List all the documents which has been created.
students> db.data.find()
[
{
_id: ObjectId("64fabf5c7d6e92e1e0d959f7"),
name: 'Prabin',
age: 22
},
{ _id: ObjectId("64fabff57d6e92e1e0d959f8"), name: 'Ashok', age: 23 },
{
_id: ObjectId("64fabff57d6e92e1e0d959f9"),
name: 'Shubham',
age: 24
}
]
When to use quotes and when not to ?
- If the field name contains the special characters or spaces, or starts with a numberic digit, using quotes is necessary.
- If the field name is a reserved keyword in MongoDB, use quotes to distinguish it from the reserved keyword.
Ordered and Unordered Inserts
When executing bulk write operations, 'ordered' and 'unordered' determine the batch behaviour.
- Ordered inserts: Default behaviour is ordered inserts, where MongoDB can stops on first order.
- Unordered inserts: When executing bulk write operations with unordered flag, MongoDB can do processing after encountering an error.
students> db.data.insertMany([{'name': 'Rahul', age:23 }, {'name': 'Abhishek', age: 24}], {"ordered": false});
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64fac3ed7d6e92e1e0d959fa"),
'1': ObjectId("64fac3ed7d6e92e1e0d959fb")
}
}
Case Sensitivity in MongoDB
- Collection Name are case sensitive.
- Field names in the document is also case sensitive.