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.

Updated on: 30-Jul-2019

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements