Mongo投影结果作为选定项的数组

2024-10-05 12:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

对于mongo中给定的文档

{"_id" : "joe":  
  grocerylist: [ "cheddar", "apple", "oranges" ]
} 
{"_id" : "joanna":  
grocerylist: [ "cheddar", "foobar" ]
}
{"_id" : "john": 
grocerylist: [ "apple", "oranges" ]
}

如果我搜索列表中有切达干酪的用户

find({"grocerylist" : cheddar}, fields={'_id' : 1}) 

我明白了

[{u'_id': u'joe'}, {u'_id': u'joanna'}]

使用Mongo,我怎么能得到一个匹配用户的列表,像这样。。你知道吗

[u'joe', u'joanna']

谢谢。你知道吗


Tags: 用户文档idapple列表mongofindjohn
2条回答

一种选择是使用列表:

cursor = db.col.find({"grocerylist" : cheddar}, fields={'_id' : 1}) 
print([document['user'] for document in cursor])

_id在整个集合中是唯一的,因此您可以在这里使用^{}。你知道吗

collection.distinct('_id', {'grocerylist' : cheddar})

相关问题 更多 >

    热门问题