How Retrieve data from MongoDB if the data is only at a specific position

Viewed 24

Suppose you have the following documents in my collection:

db.myCollection.insert({
    "VEHICLE": {
        "registration": "000XX",
        "capacity": "50000",
        "weight": "400",
        "status": "AVAILABLE"
    }
});

db.myCollection.insert({
    "EMPLOYEE": {
        "e#": "007",
        "name": "James Bond",
        "dob": "",
        "address": "England, UK",
        "hiredate": "01-APR-69",
        "position": "secret agent",
        "licence": "00001",
        "status": "AVAILABLE",
        "trips": [{
                   "trip number": "1",
                   "registration": "0023SAD",
                   "trip date": "19-MAR-99",
                   "legs": ["Kotte", "Baddagana", "London", "Darby"]
         }, {
                   "trip number": "3",
                   "registration": "KKK007",
                   "trip date": "12-MAR-95",
                   "legs": ["Darby", "Thalawa", "Kotte", "Baddagana"]
    }]
}

});

I want to find the names of the employees who started their journey from Kotte

This query below gives me all data that has the word Kotte in legs

db.myCollection.find({"EMPLOYEE.trips.legs":"Kotte"},{"EMPLOYEE.name":1, "_id":0}).pretty()

How do I edit the above query to only give me results if the first value of the legs is Kotte

1 Answers

Try to filter only legs first element by adding .0 in your filter:

db.myCollection
  .find({ 'EMPLOYEE.trips.legs.0': 'Kotte', 'EMPLOYEE.name': 1, _id: 0 })
  .pretty();
Related