简体   繁体   English

使用 Python dict 查询 mongo 集合

[英]Query mongo collection using Python dict

My MongoDB documents look like:我的 MongoDB 文档如下所示:

{
  'x': 1,
  'y': 2,
  'z': 3
},
{
  'x': 10,
  'y': 20,
  'z': 30
},
{
  'x': 100,
  'y': 200,
  'z': 300
},

and the queries look like:和查询看起来像:

query_1 = {
  'x': [1, 100]
}

query_2 = {
'x': [10],
'z': [2]
}

Unfortunately, when we do collection.find(query_1) or collection.find(query_2) , we get no results which is because of the lists in the queries.不幸的是,当我们执行collection.find(query_1)collection.find(query_2) ,我们没有得到任何结果,这是因为查询中的列表。 How can I make Mongo take my queries?如何让 Mongo 接受我的查询? Please note that the 'values' of my query dictionaries are always lists.请注意,我的查询词典的“值”始终是列表。

EDIT:编辑:

Expanding on Belly Buster's answer below, I believe if I do:扩展下面的 Belly Buster 的答案,我相信如果我这样做:

{
'$or': [
         {'x': {'$in': ['item1', 'item2']}},
         {'y': {'$in': ['item1', 'item2']}}
        ]
}

answers my question.回答我的问题。 However, I feel that there is a better way to achieve this.但是,我觉得有更好的方法来实现这一目标。 Is there?在那儿?

Query 1 you are searching on a field x that contains a list [1, 100] .您正在搜索包含列表[1, 100]的字段x查询 1。 As there aren't any records matching, you get no results.由于没有任何记录匹配,因此您不会得到任何结果。 Now if you wanted to search x for either 1 or 100, you need to use the $in operator;现在,如果您想在x中搜索 1 或 100,则需要使用$in运算符; your query should be:您的查询应该是:

result = db.mycollection.find({'x': {'$in': [1, 100]}})

Query 2 you are searching on a field x containing a list [10] and a field z containing a list [2] .查询 2 您正在搜索包含列表[10]的字段x和包含列表[2]的字段z Again there's nothing matching that in your data.同样,您的数据中没有任何匹配的内容。

I'm not sure what query you are trying to perform for this, but if it is x == 10 or z == 2 , then your query is :我不确定您要为此执行什么查询,但如果它是x == 10 or z == 2 ,那么您的查询是:

result = db.mycollection.find({'$or': [{'x': 10}, {'z': 2}]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM