使用python在mongodb中找到具有特定数组索引的项目的文档

时间:2017-02-23 19:54:37

标签: python mongodb pymongo

我有数据库;

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"
       }
}

我希望使用python在Apple数据库文档中的0th类别数组索引处找到Mongo的文档。我正在尝试这种方式;

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

打印相同的结果但如何指定Categories数组的索引?我没有在collection.find({"Categories" : "Apple"})中指定类别索引

1 个答案:

答案 0 :(得分:1)

仅匹配索引0:

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