Retrieve the position in an Array in MongoDB?

MongoDBDatabaseBig Data Analytics

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
}
raja
Published on 21-May-2019 08:43:40
Advertisements