[英]Mongo DB query on multiple conditions
I am trying to do a simple query based on two conditions in MongoDB using pymongo.我正在尝试使用 pymongo 基于 MongoDB 中的两个条件进行简单查询。
I am using the sample restaurants data set from the tutorial documentation.我正在使用教程文档中的示例餐厅数据集。 I have:我有:
from pymongo import MongoClient
import pymongo
import pandas as pd
client = MongoClient()
db = client.test
cursor = db.restaurants.find({"$and":[{'borough':"Manhattan"},{"grades":{'grade':"A"}}]}
for record in cursor:
print record
I am just trying to print all the restaurants in Manhattan with a grade of 'B.'我只是想用“B”的等级打印曼哈顿的所有餐馆。 But this pulls back no results.但这没有任何结果。 I have also tried我也试过
cursor = db.restaurants.find({"borough":"Manhattan", "grades.grade":"B"})
but this will only filter by the first condition and won't filter by the "grade."但这只会按第一个条件过滤,而不会按“等级”过滤。 It's exactly how it is laid out in the documentation but I can't get it to work.这正是它在文档中的布局方式,但我无法让它工作。
The problem is in the second condition.问题出在第二种情况。 grades
is a subarray of grades , use $elemMatch
: grades
是一个档次的子阵列,使用$elemMatch
:
db.restaurants.find({"$and": [{"borough": "Manhattan"}, {"grades": {"$elemMatch": {"grade": "A"}}}]})
Works for me.为我工作。
I had a similar issue and it worked for me with the following syntax:我有一个类似的问题,它使用以下语法对我有用:
result = db.mycollection.find({"$and": [{"key1": value1}, {"key2": value2}]})
I have multiple records with the same value under key1
, but I want the only one with specific value on key2
.我在key1
下有多个具有相同值的记录,但我想要唯一一个在key2
上具有特定值的记录。 It seems to work for me.它似乎对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.