这是我正在处理的文档的示例:
{
"_id" : ObjectId("5b35019563726438989381d3"),
"ref" : "123",
"nom" : "pc",
"Revendeurs" : [
{
"revendeur" : "Tdiscount",
"selecteur_prix" : ".price",
"hist_prix" : [
{
"date" : ISODate("2018-06-28T00:00:00Z"),
"prix" : 200
},
{
"date" : ISODate("2018-06-27T00:00:00Z"),
"prix" : 100.8}
]
}
]
}
我想查询“prix”字段的最大值。 我还需要列出“revendeur”的所有“prix”但是 Mongodb 仅返回空结果。
执行此查询时:
db.Tunicompare.aggregate([
{ $unwind: '$Revendeurs' },
{ $group: { _id: null, max: { $max: '$Revendeurs.hist_prix.prix' } } },
{ $project: { max: 1, _id:0 } }
])
我得到了这个结果(而不是最多只得到 200)
{ "max" : [ 200, 100.8 ] }
最佳答案
如果你想在外部和内部列表中找到最大值,做这样的事情(全局最大值):
db.Tunicompare.aggregate([
{ $unwind: '$Revendeurs' },
{ $unwind: '$Revendeurs.hist_prix' },
{ $group: { _id: null, max: { $max: '$Revendeurs.hist_prix.prix' } } },
{ $project: { max: 1, _id:0 } }
])
输出
/* 1 */
{
"max" : 200.0
}
关于mongodb - 如何在 MongoDB 中查询子子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100843/