我有一个MongoDB集合,其文档格式如下:
result of MyCollection.find({"_id": "20141029"})
{
"_id" : "20141029",
"portfolio_returns" : [
{
"data" : [
{
"report" : {
"open" : {
"returns_rs" : 398.8
},
"both" : {
"returns_rs" : 1054.800
}
},
"portfolio" : "Mystocks"
}
],
"user" : "mzmmohideen@gmail.com"
},
{
"data" : [
{
"report" : {
"open" : {
"returns_rs" : 5000
},
"both" : {
"returns_rs" : 5500
}
},
"portfolio" : "pff"
}
],
"user" : "mani@ithoughtz.com"
}
],
'portfolio_stock_gain_or_loss': [
{
"data" : [
{
"portfolio" : "gm",
"stocks" : [ ]
}
],
"user" : "moorthy.gm@gmail.com"
},
{
"data" : [
{
"portfolio" : "Mystocks",
"stocks" : [
{
"open" : {
"returns_rs" : 9144
},
"scripcode" : "532540",
"both" : {
"returns_rs" : 9426.75
}
},
{
"open" : {
"returns_rs" : 254.80
},
"scripcode" : "500790",
"both" : {
"returns_rs" : 254.80
}
}
]
}
],
"user" : "mzmmohideen@gmail.com"
},
{
"data" : [
{
"portfolio" : "pff",
"stocks" : [
{
"open" : {
"returns_rs" : 4000
},
"scripcode" : "500790",
"both" : {
"returns_rs" : 8500
}
},
{
"open" : {
"returns_rs" : 0
},
"scripcode" : "533151",
"both" : {
"returns_rs" : 0
}
}
]
}
],
"user" : "mani@ithoughtz.com"
}
]
}
我的问题是如何使用pymongo过滤出来自此文档的数据,其中“portfolio_stock_gain_or_loss.data.stocks.open.returns_rs”大于1000。
期待出局是
{
"_id" : "20141029",
'portfolio_stock_gain_or_loss': [
{
"data" : [
{
"portfolio" : "Mystocks",
"stocks" : [
{
"open" : {
"returns_rs" : 9144
},
"scripcode" : "532540",
"both" : {
"returns_rs" : 9426.75
}
}
]
}
],
"user" : "mzmmohideen@gmail.com"
},
{
"data" : [
{
"portfolio" : "pff",
"stocks" : [
{
"open" : {
"returns_rs" : 4000
},
"scripcode" : "500790",
"both" : {
"returns_rs" : 8500
}
},
]
}
],
"user" : "mani@ithoughtz.com"
}
]
}
有关如何在现有数据上执行此操作或我是否需要更改格式的任何想法?
非常感谢
答案 0 :(得分:2)
您的mongo文档太嵌套了我认为如果可能,您应该重新构建您的mongo文档。否则,如果您想继续使用相同的文档,那么mongo聚合可以帮助解决您的问题。我写下面的mongo聚合我觉得它解决了你的问题
db.MyCollection.aggregate([
{"$unwind":"$portfolio_stock_gain_or_loss"},
{"$unwind":"$portfolio_stock_gain_or_loss.data"},
{"$unwind":"$portfolio_stock_gain_or_loss.data.stocks"},
{"$project":{"openStock":"$portfolio_stock_gain_or_loss.data.stocks.open","data":"$portfolio_stock_gain_or_loss.data"}},
{"$match": {"openStock.returns_rs":{"$gt":1000}}} ]).pretty()