我的mongo集合包含以下文档:
{
"_id" : ObjectId("52de74863fcc41ddfc7b23a5"),
"ts" : "1385969614848",
"Info" : [
{
"out" : 0,
"Type" : "1",
"Descr" : "Null0",
},
{
"out" : 10,
"Type" : "1",
"Descr" : "Null",
},
{
"out" : 20000,
"Type" : "1",
"Descr" : "Null0",
},
{
"out" : 70,
"Type" : "10",
"Descr" : "abc",
}
]
}
{
"_id" : ObjectId("52de74863fcc41ddfc7b23a6"),
"ts" : "1385969614852",
"Info" : [
{
"out" : 500,
"Type" : "1",
"Descr" : "Null0",
},
{
"out" : 100,
"Type" : "1",
"Descr" : "Null",
},
{
"out" : 2896,
"Type" : "1",
"Descr" : "Null0",
},
{
"out" : 4052,
"Type" : "10",
"Descr" : "abc",
}
]
}
我想按键“out”排序。为此,我编写了以下mongo查询:
db.collection_name.find({},{"Info.out":1}).sort({"Info.out":1}).pretty()
然后显示以下输出:
{
"_id" : ObjectId("52fa2922d73ddc832323f402"),
"Info" : [
{
"out" : 0
},
{
"out" : 10
},
{
"out" : 20000
},
{
"out" : 70
}
]
}
{
"_id" : ObjectId("52fa292ed73ddc832323f403"),
"Info" : [
{
"out" : 500
},
{
"out" : 100
},
{
"out" : 2896
},
{
"out" : 4052
}
]
}
但是,我期望下面的输出:
{
"_id" : ObjectId("52fa2922d73ddc832323f402"),
"Info" : [
{
"out" : 20000
},
{
"out" : 70
},
{
"out" : 10
},
{
"out" : 0
}
]
}
{
"_id" : ObjectId("52fa292ed73ddc832323f403"),
"Info" : [
{
"out" : 4052
},
{
"out" : 2896
},
{
"out" : 500
},
{
"out" : 100
}
]
}
有谁知道如何达到所需的输出?
答案 0 :(得分:3)
使用以下aggregation framework操作:
db.collection.aggregate([
{$project: {_id:1, out: "$Info.out"} },
{$unwind: "$out"},
{$sort: {_id:1, "out":-1} },
{$group: {_id:"$_id" , "Info": { $push: {"out":"$out"}} } }
])
产生
{
"result" : [
{
"_id" : ObjectId("52de74863fcc41ddfc7b23a6"),
"Info" : [
{
"out" : 4052
},
{
"out" : 2896
},
{
"out" : 500
},
{
"out" : 100
}
]
},
{
"_id" : ObjectId("52de74863fcc41ddfc7b23a5"),
"Info" : [
{
"out" : 20000
},
{
"out" : 70
},
{
"out" : 10
},
{
"out" : 0
}
]
}
],
"ok" : 1
}
您可能还想查看:
db.collection.aggregate([
{$project: {_id:1, out: "$Info.out"} },
{$unwind: "$out"},
{$sort: {_id:1, "out":-1} },
{$group: {_id:"$_id" , "Info": { $push: "$out"} } }
])
将每个文档中的信息输出为" clean"阵列:
{
"_id" : ObjectId("52de74863fcc41ddfc7b23a6"),
"Info" : [
4052,
2896,
500,
100
]
}