MongoDB query to get record beginning with specific element from an array?

MongoDBDatabaseBig Data Analytics

You can use dot(.) notation along with array index to get record beginning with specific element. Let us first create a collection with documents −

>db.arrayStartsWithElementDemo.insertOne({"PlayerName":"Chris","PlayerScore":[780,9000,456,789,987]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd29fed345990cee87fd889")
}
>db.arrayStartsWithElementDemo.insertOne({"PlayerName":"Robert","PlayerScore":[890,670,890,54646,42424]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a00c345990cee87fd88a")
}
>db.arrayStartsWithElementDemo.insertOne({"PlayerName":"David","PlayerScore":[909090,896555,3344433,78900]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a025345990cee87fd88b")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd29fed345990cee87fd889"),
   "PlayerName" : "Chris",
   "PlayerScore" : [
      780,
      9000,
      456,
      789,
      987
   ]
}
{
   "_id" : ObjectId("5cd2a00c345990cee87fd88a"),
   "PlayerName" : "Robert",
   "PlayerScore" : [
      890,
      670,
      890,
      54646,
      42424
   ]
}
{
   "_id" : ObjectId("5cd2a025345990cee87fd88b"),
   "PlayerName" : "David",
   "PlayerScore" : [
      909090,
      896555,
      3344433,
      78900
   ]
}

Following is the query to get array beginning with specific elements 890 and then 670 −

> db.arrayStartsWithElementDemo.find({"PlayerScore.0" : 890, "PlayerScore.1" : 670}).pretty();

This will produce the following output. Here,

{
   "_id" : ObjectId("5cd2a00c345990cee87fd88a"),
   "PlayerName" : "Robert",
   "PlayerScore" : [
      890,
      670,
      890,
      54646,
      42424
   ]
}
raja
Published on 22-May-2019 09:30:37
Advertisements