[英]How to query a sub sub document in MongoDB?
以下是我正在處理的文檔的示例:
{
"_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
}
隨着$減少 。 嘗試一下MongoPlayground :
db.collection.aggregate([
{
$unwind: "$Revendeurs"
},
{
$group: {
_id: null,
prixArr: {
$push: "$Revendeurs.hist_prix.prix"
}
}
},
{
$project: {
"_id": 0,
"max": {
$reduce: {
input: "$prixArr",
initialValue: 0,
in: {
$max: "$$this"
}
}
}
}
}
])
輸出:
[
{
"max": 200
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.