Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Retrieve the position in an Array in MongoDB?



You can use the concept of map reduce to get the position in an array. Let us first create a collection with documents −

> db.retrievePositionDemo.find();
{ "_id" : ObjectId("5cd569ec7924bb85b3f4893f"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] }

Following is the query to display all documents from a collection with the help of find() method −

> db.retrievePositionDemo.find().pretty();

This will produce the following output −

{
    "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
    "Subjects" : [
       "MySQL",
       "MongoDB",
        "Java"
    ]
}

Following is the query to retrieve the position in an array in MongoDB −

> db.retrievePositionDemo.mapReduce(
...     function() {
...         emit(this._id,{ "IndexValue": this.Subjects.indexOf("MongoDB") });
...     },
...     function() {},
...     {
...         "out": { "inline": 1 },
...         "query": { "Subjects":"MongoDB"}
...     }
... );

This will produce the following output −

{
   "results" : [
      {
        "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
         "value" : {
            "IndexValue" : 1
         }
      }
   ],
   "timeMillis" : 662,
   "counts" : {
      "input" : 1,
      "emit" : 1,
      "reduce" : 0,
      "output" : 1
   },
   "ok" : 1
}

Look at the above sample output, the index or position of value “MongoDB” is 1. You can check for value “Java”, which is at position 2 −

> db.retrievePositionDemo.mapReduce(
...     function() {
...         emit(this._id,{ "IndexValue": this.Subjects.indexOf("Java") });
...     },
...     function() {},
...     {
...         "out": { "inline": 1 },
...         "query": { "Subjects":"MongoDB"}
...     }
... );

This will produce the following output −

{
   "results" : [
      {
         "_id" : ObjectId("5cd569ec7924bb85b3f4893f"),
         "value" : {
            "IndexValue" : 2
         }
      }
   ],
   "timeMillis" : 30,
   "counts" : {
      "input" : 1,
      "emit" : 1,
      "reduce" : 0,
      "output" : 1
   },
   "ok" : 1
}
Updated on: 2019-07-30T22:30:26+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements