查询:
db.environments.aggregate(
[{$match:{customer:"CustomerName"}},
{$group:{_id:{environment: "$environment",
cpu_oversubscription:"$cpu_oversubscription",
memory_oversubscription:"$memory_oversubscription"}}} ])
当我运行查询时,只显示环境和CPU_oversubcription字段,不显示内存字段。
这是我得到的输出:
[{"_id":{"environment":"V&B","cpu_oversubscription":1}}
当我运行db.environments.find()
时,我会看到所有字段
[{"_id":{"environment":"V&B","cpu_oversubscription":1,"memory_oversubscription":1,"customer":"CustomerName"}}
我的查询有什么问题?
修改:完全查询
Environment.aggregate([{$match:{customer:req.query.customer}},{$group:{_id:{environment: "$environment",cpu_oversubscription:"$cpu_oversubscription",memory_oversubscription:"$memory_oversubscription",}}} ])
查询的确切结果
{ "_id" : { "environment" : "1", "cpu_oversubscription" : 1 } }
{ "_id" : { "environment" : "2", "cpu_oversubscription" : 4 } }
{ "_id" : { "environment" : "3", "cpu_oversubscription" : 4 } }
{ "_id" : { "environment" : "4", "cpu_oversubscription" : 4 } }
{ "_id" : { "environment" : "5", "cpu_oversubscription" : 4 } }
{ "_id" : { "environment" : "6", "cpu_oversubscription" : 1 } }
{ "_id" : { "environment" : "7", "cpu_oversubscription" : 1 } }
{ "_id" : { "environment" : "8", "cpu_oversubscription" : 1 } }
{ "_id" : { "environment" : "9", "cpu_oversubscription" : 4 } }
{ "_id" : { "environment" : "10", "cpu_oversubscription" : 4 } }
db.environments.find()的确切结果(仅限第一个结果)
{ "_id" : ObjectId("560a5139b56a71ea60890201"), "customer" : "CustomerName", "environment" : "1", "memory_oversubcription" : 1, "cpu_oversubscription" : 1 }
答案 0 :(得分:0)
正如@Yogesh所说,您的数据中存在拼写错误。这解决了你的问题。
尽管如此,您不需要此查询的聚合框架: 使用投影的 find 会更有效率:
db.environments.find({ "customer" : "CustomerName" },
{ _id : 0, "environment" : 1,
"memory_oversubscription" : 1,
"cpu_oversubscription" : 1
})
结果将是:
{
"environment" : "1",
"memory_oversubscription" : 1,
"cpu_oversubscription" : 1
}
如果由于某些原因你真的想在_id字段下得到结果,那么$ project会更好:
db.environments.aggregate([
{$match:{"customer" : "CustomerName"}},
{$project:
{_id :
{"environment" : "$environment",
"memory_oversubscription" : "$memory_oversubscription",
"cpu_oversubscription" : "$cpu_oversubscription"}
}
}
]);
结果:
{ "_id" : { "environment" : "1",
"memory_oversubscription" : 1,
"cpu_oversubscription" : 1 }
}
对我没有意义,但也许它适合你: - )。