1

我有一个结构

locations : { //info,
             "events" :[ { //data
                          "displayed" : True},
                          { //data
                          "displayed" : False}
                       ]
             }

每个位置都有许多事件,我们在其中定义是否显示事件。

我的python代码:

#load the data
locations = db.col.find({'events.displayed': True})
#remove manually
for l in locations:
    for e in l['events']:
        if e['displayed'] == False:
            #this item should be deleted
            print e

我知道如果只有 a为真并且它将返回整个项目,则{'events.displayed': True}可以满足此要求。events.displayed

我想问一下我是否可以在find()通话中忽略那些带有"displayed" : False. 如果 pymongo 不会发生这种情况,我想用"displayed" : False优化的(因为双循环)方式使用 python 手动删除项目(可能是 itertools 库的东西?)。

4

2 回答 2

0

好吧,您只能"displayed": True使用 MongoDB 的Aggregation Framework获取这些项目。这是一个示例代码。

db.locations.aggregate([{'$unwind': '$events'}, {'$match': {'events.displayed': True}}])

db.locations.find您必须在 Python 代码中过滤这些元素。

于 2013-10-31T01:43:23.777 回答
0

使用“投影”告诉服务器只发送数组的匹配部分:

for doc in locations.find(
        {'events.displayed': True},
        {'events': {'$elemMatch': {'displayed': True}}}):
    print doc

请注意,这仅返回第一个匹配的数组元素。如果你需要所有匹配的元素,你的 Python 循环是最好的选择。

于 2013-11-05T17:17:00.600 回答