我有一个带有文档的mongo集合,如下所示:-
{
"_id" : ObjectId("55a9378ee2874f0ed7b7cb7e"),
"_uid" : 10,
"impressions" : [
{
"pos" : 6,
"id" : 123,
"service" : "furniture"
},
{
"pos" : 0,
"id" : 128,
"service" : "electronics"
},
{
"pos" : 2,
"id" : 127,
"service" : "furniture"
},
{
"pos" : 2,
"id" : 125,
"service" : "electronics"
},
{
"pos" : 10,
"id" : 124,
"service" : "electronics"
}
]
},
{
"_id" : ObjectId("55a9378ee2874f0ed7b7cb7f"),
"_uid" : 11,
"impressions" : [
{
"pos" : 1,
"id" : 124,
"service" : "furniture"
},
{
"pos" : 10,
"id" : 124,
"service" : "electronics"
},
{
"pos" : 1,
"id" : 123,
"service" : "furniture"
},
{
"pos" : 21,
"id" : 122,
"service" : "furniture"
},
{
"pos" : 3,
"id" : 125,
"service" : "electronics"
},
{
"pos" : 10,
"id" : 121,
"service" : "electronics"
}
]
}
我的目标是找到特定"service"
(比如"furniture"
(中的所有"id"
,即得到这样的结果:
[122,123,124,127]
但我不知道如何在中框定条件
db.collection_name.find()
因为很难为数组中的第'n'个元素"impressions[n]":"value"
。
一种选择是使用获得的"id"
执行聚合操作来查找服务的每个"id"
的印象,正如我之前问的这个问题的答案所建议的那样:-PyMongo中的MapReduce。
但我只想要服务中不同'id'
的列表,而不是印象。请帮忙!
您需要聚合框架来获得有意义的结果。就像这样:
result = db.collection.aggregate([
{ "$match": {
"impressions.service": "furniture"
}},
{ "$unwind": "$impressions" },
{ "$match": {
"impressions.service": "furniture"
}},
{ "$group": {
"_id": "$impressions.id"
}}
])
或者更好的是使用MongoDB 2.6或更高版本,它可以使用$redact
删除与$unwind
"之前"不匹配的数组项:
result = db.collection.aggregate([
{ "$match": {
"impressions.service": "furniture"
}},
{ "$redact": {
"$cond": {
"if": {
"$eq": [
{ "$ifNull": [ "$service", "furniture" ] },
"furniture"
]
},
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}},
{ "$unwind": "$impressions" },
{ "$group": {
"_id": "$impressions.id"
}}
])
哪个收益率:
{ "_id" : 122 }
{ "_id" : 124 }
{ "_id" : 127 }
{ "_id" : 123 }
不是一个简单的"列表",而是对其进行转换,因此:
def mapper (x):
return x["_id"]
map(mapper,result)
或者:
map(lambda x: x["_id"], result)
给你:
[122, 124, 127, 123]
如果希望对其进行"排序",则在聚合管道的末尾添加$sort
阶段,或者在代码中对结果列表进行排序。