我现在使用mongodb来获得我想要的东西。
{
"_id" : ObjectId("533b66f3e4b038c01f6a427f"),
"ccNameCount" : [{
"ccName" : "ATCC",
"paperCount" : 4660,
"strainCount" : 9339,
"version" : 1
}, {
"ccName" : "BCC",
"paperCount" : 24,
"strainCount" : 41
}, {
"ccName" : "BCCM/DCG",
"paperCount" : 3,
"strainCount" : 7
}]
}
示例文档就是这样。现在,我想查询ccNameCount.ccName=ATCC的文档,并按paperCount对结果进行排序。但当然,由于ccNameCount是一个数组,所以只按ccNameCount键排序不会得到我想要的结果。所以,我的问题是,我能做什么?使用MapReduce?
您的最佳选择是聚合框架:
db.collection.aggregate([
// Match the "documents" that contain your condition
// reduces the working size
{ "$match": {
"ccNameCount.ccName": "ATCC"
}},
// Keep the original document, you might not really care about this
{ "$project": {
"_id": {
"_id": "$_id",
"ccNameCount": "$ccNameCount"
},
"ccNameCount": 1
}},
// Unwind the array to de-normalize
{ "$unwind": "$ccNameCount" },
// Now just match those elements (now documents) as your condition
{ "$match": {
"ccNameCount.ccName": "ATCC"
}},
// Sort the results on the now selected "paperCount"
{ "$sort": { "ccNameCount.paperCount": -1 } },
// Put the documents back to normal if you want
{ "$project": {
"_id": "$_id._id",
"ccNameCount": "$_id.ccNameCount"
}}
])
因此,在这实际上"选择"了匹配的数组元素之后,结果就可以按照这个位置的字段进行排序。如果您想在结果中返回数组的原始状态,$project
阶段是可选的,否则阶段只选择匹配的条目并正确排序