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

To query records beginning with specific elements from an array in MongoDB, use dot notation with array index positions to match exact values at specific positions within the array.

Syntax

db.collection.find({
    "arrayField.0": value1,
    "arrayField.1": value2,
    "arrayField.n": valueN
});

Sample Data

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

Example: Find Array Beginning with Specific Elements

Find records where the PlayerScore array starts with 890 at index 0 and 670 at index 1 ?

db.arrayStartsWithElementDemo.find({
    "PlayerScore.0": 890,
    "PlayerScore.1": 670
});
{
    "_id": ObjectId("5cd2a00c345990cee87fd88a"),
    "PlayerName": "Robert",
    "PlayerScore": [890, 670, 890, 54646, 42424]
}

How It Works

  • "PlayerScore.0": 890 matches documents where the first array element equals 890
  • "PlayerScore.1": 670 matches documents where the second array element equals 670
  • Both conditions must be satisfied (AND operation) for the document to match

Conclusion

Use dot notation with index positions to query arrays beginning with specific elements. This approach provides exact positional matching for precise array filtering in MongoDB.

Updated on: 2026-03-15T01:02:22+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements