Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert to specific index for MongoDB array?
To insert a specific index for MongoDB array, you can use $push operator. Let us create a collection with documents
>db.insertToSpecificIndexDemo.insertOne({"StudentName":"Larry","StudentSubjects":["MySQL","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2562a629b87623db1b2c")
}
>db.insertToSpecificIndexDemo.insertOne({"StudentName":"Chris","StudentSubjects":["C++","C"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9d2573a629b87623db1b2d")
}
Following is the query to display all documents from a collection with the help of find() method
> db.insertToSpecificIndexDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9d2562a629b87623db1b2c"),
"StudentName" : "Larry",
"StudentSubjects" : [
"MySQL",
"Java"
]
}
{
"_id" : ObjectId("5c9d2573a629b87623db1b2d"),
"StudentName" : "Chris",
"StudentSubjects" : [
"C++",
"C"
]
}
Following is the query to insert to a specific index for MongoDB array in _id “5c9d2573a629b87623db1b2d”
> db.insertToSpecificIndexDemo.update(
... { _id: ObjectId("5c9d2573a629b87623db1b2d")},
... { $push: {
... StudentSubjects: {
... $each: [ {"CoreSubject": "MongoDB"} ],
... $position: 0
... }
... }}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the value is inserted into the specific position or not. Above, we have given index 0 that would mean insertion in the beginning
> db.insertToSpecificIndexDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9d2562a629b87623db1b2c"),
"StudentName" : "Larry",
"StudentSubjects" : [
"MySQL",
"Java"
]
}
{
"_id" : ObjectId("5c9d2573a629b87623db1b2d"),
"StudentName" : "Chris",
"StudentSubjects" : [
{
"CoreSubject" : "MongoDB"
},
"C++",
"C"
]
}
Look at the sample output, the “CoreSubject”:”MongoDB” is inserted at the beginning in the MongoDB array.
Advertisements