【发布时间】:2014-11-06 13:08:17
【问题描述】:
我将以下两项插入到集合“框架”中:
frame1 = {
"number": 1,
"hobjects": [ { "htype": 1, "weight": 50 },
{ "htype": 2, "weight": 220 },
{ "htype": 2, "weight": 290 },
{ "htype": 3, "weight": 450 } ],
"sobjects": [ { "stype": 1, "size": 10.0 },
{ "stype": 2, "size": 5.1 },
{ "stype": 2, "size": 6.5 } ],
}
frame2 = {
"number": 2,
"hobjects": [ { "htype": 1, "weight": 61 },
{ "htype": 2, "weight": 210 },
{ "htype": 2, "weight": 250 } ],
"sobjects": [ { "stype": 1, "size": 12.1 },
{ "stype": 2, "size": 4.9 },
{ "stype": 2, "size": 6.2 },
{ "stype": 2, "size": 5.7 } ],
}
frames.insert(frame1)
frames.insert(frame2)
现在我想查询部分帧数据:
query = { "hobjects.htype": 3, "sobjects.stype": 2 }
db.frames.find(query)
导致:
{u'_id': ObjectId('545b6ea7b9ad9a03462d743b'), u'hobjects': [{u'htype': 1, u'weight': 50}, {u'htype': 2, u'weight': 220}, {u'htype': 2, u'weight': 290}, {u'htype': 3, u'weight': 450}], u'number': 1, u'sobjects': [{u'stype': 1, u'size': 10.0}, {u'stype': 2, u'size': 5.1}, {u'stype': 2, u'size': 6.5}]}
这不是我真正想要的。我想根据查询过滤集合,以便得到以下结果:
{u'_id': ObjectId('545b6ea7b9ad9a03462d743b'), u'hobjects': [{u'htype': 3, u'weight': 450}], u'number': 1, u'sobjects': [{u'stype': 2, u'size': 5.1}, {u'stype': 2, u'size': 6.5}]}
我发现的唯一解决方案是对每个集合进行展开和分组的聚合:
query = { "hobjects.htype": 3, "sobjects.stype": 2 }
db.frames.aggregate([
{ "$match": query },
{ "$unwind": "$hobjects" },
{ "$match": dict((key, value) for key, value in query.iteritems() if "hobjects." in key) },
{ "$group": { "_id": "$_id", "number": { "$first": "$number" } , "hobjects": { "$push": "$hobjects" }, "sobjects": { "$first": "$sobjects" } } },
{ "$unwind": "$sobjects" },
{ "$match": dict((key, value) for key, value in query.iteritems() if "sobjects." in key) },
{ "$group": { "_id": "$_id", "number": { "$first": "$number" } , "hobjects": { "$first": "$hobjects" }, "sobjects": { "$push": "$sobjects" } } },
])
我想这不是一种非常有效和灵活的查询方式。不知道有没有其他选择?
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework