假设我有以下集合:
{ _id: 1, Array: [
{ K: "A", V: 8 },
{ K: "B", V: 5 },
{ K: "C", V: 13 } ] }
{ _id: 2, Array: [
{ K: "D", V: 12 },
{ K: "E", V: 14 },
{ K: "F", V: 2 } ] }
我想运行一个查询,返回具有最高"V"的子文档,所以在这种情况下,我会得到:
{ _id: 1, Array: [ { K: "E", V: 14 } ] }
或者简单地说:
{ K: "E", V: 14 }
重要的是,我希望Mongo服务器上的内存使用率为O(1)(无论我处理多少文档,内存使用率都是恒定的),我只想检索到一个具有所需值的子文档(我不想下载超过必要数量的子文档)。
我的首选方法是使用简单的查找查询,但我不确定这是否可行。我怀疑这也可以通过聚合框架(或者map reduce?)来实现,但不知道如何实现。我不希望结果存储在临时集合中,而是直接返回给我的客户端(就像普通查询一样)。
下面的加积集返回您需要的内容。
db.letters.aggregate([
{$project:{"Array.K":1, "Array.V":1}},
{$unwind:"$Array"},
{$sort:{"Array.V":-1}},
{$limit:1}
]);
退货:
{"_id":2, "Array":{"K":"E","V":14}}
享受吧!:)
正如@JohnnyHK所说:
db.col.aggregate([
{$unwind: '$Array'},
{$group: {_id: '$_id', Array: {K: {$max: '$K'}, V: {$max: '$V'}}}}
])
类似的东西。
IN Simple Words,如果您有mongo查询响应类似以下内容-并且您只想要Array->"Wish_CreatedDate"中的最高值
{
"_id": "57ee5a708e117c754915a2a2",
"TotalWishs": 3,
"Events": [
"57f805c866bf62f12edb8024"
],
"wish": [
"Cosmic Eldorado Mountain Bikes, 26-inch (Grey/White)",
"Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
"Suunto Digital Black Dial Unisex Watch - SS018734000"
],
"Wish_CreatedDate": [
"2017-03-05T00:00:00.000Z",
"2017-02-13T00:00:00.000Z"
],
"UserDetails": [
{
"createdAt": "2016-09-30T12:28:32.773Z",
"jeenesFriends": [
"57edf8a96ad8f6ff453a384a",
"57ee516c8e117c754915a26b",
"58a1644b6c91d2af783770b0",
"57ef4631b97d81824cf54795"
],
"userImage": "user_profile/Male.png",
"email": "roopak@small-screen.com",
"fullName": "Roopak Kapoor"
}
],
},
***然后你必须添加
最晚创建日期:{$max:"$Wish_CreatedDate"},
像下面这样的东西-
{
$project : { _id: 1,
TotalWishs : 1 ,
wish:1 ,
Events:1,
Wish_CreatedDate:1,
Latest_Wish_CreatedDate: { $max: "$Wish_CreatedDate"},
}
}
最终查询响应将低于
{
"_id": "57ee5a708e117c754915a2a2",
"TotalWishs": 3,
"Events": [
"57f805c866bf62f12edb8024"
],
"wish": [
"Cosmic Eldorado Mountain Bikes, 26-inch (Grey/White)",
"Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
"Suunto Digital Black Dial Unisex Watch - SS018734000"
],
"Wish_CreatedDate": [
"2017-03-05T00:00:00.000Z",
"2017-02-13T00:00:00.000Z"
],
"UserDetails": [
{
"createdAt": "2016-09-30T12:28:32.773Z",
"jeenesFriends": [
"57edf8a96ad8f6ff453a384a",
"57ee516c8e117c754915a26b",
"58a1644b6c91d2af783770b0",
"57ef4631b97d81824cf54795"
],
"userImage": "user_profile/Male.png",
"email": "roopak@small-screen.com",
"fullName": "Roopak Kapoor"
}
],
"Latest_Wish_CreatedDate": "2017-03-05T00:00:00.000Z"
},