Humty
Humty

Reputation: 1361

Find the document in mongodb that has an item at a specific index of array using python

I have database like;

ObjectID(234567654rtfgjytrfgfgf){
       _id : "3456ytgfewrtyhgfd"
       Categories:{
             [0] : "Apple"
             [1] : "Mango"
       }
}
ObjectID(23dfghjthrgytrfgfgf){
       _id : "67tghjgfdrthg"
       Categories:{
             [0] : "Orange"
             [1] : "Mango"
       }
}
ObjectID(23dfghjthrgytrfgfgf){
       _id : "67tghjgfdrthg"
       Categories:{
             [0] : "Apple"
             [1] : "Mango"
       }
}

I want to find the document that has the Apple at a 0th index of category array in Mongo database document using python. I am trying in this way;

cursor = collection.find({"Categories" : "Apple"})
        for document in cursor:
            print(document) 

It is printing the same result but how can I specify the index of Categories array? I am not specifying the categories index in collection.find({"Categories" : "Apple"})

Upvotes: 1

Views: 202

Answers (1)

thanasisp
thanasisp

Reputation: 5965

to match only index 0:

cursor = collection.find({"Categories.0" : "Apple"})
for document in cursor:
    print(document) 

Upvotes: 1

Related Questions