【发布时间】:2018-04-10 14:47:00
【问题描述】:
我是 mongo 的新手 我正在使用 mongo 3.6 我有一个文档结构为的集合:
{
"_id" : "236165301",
"boxID" : "431414",
"boxName" : "Test",
"packets" : [
{
"packetID" : "635665346",
"packetQty" : "5",
"packetNum" : "1",
"packetItems" : [
{
"packetItemNum" : "Ab89",
"packetItemQty" : "1",
"packetItemCode" : "6",
},
{
"packetItemNum" : "Ab90",
"packetItemQty" : "3",
"packetItemCode" : "6",
},
{
"packetItemNum" : "Ab87",
"packetItemQty" : "3",
"packetItemCode" : "8",
}
]
},
{
"packetID" : "635665380",
"packetQty" : "6",
"packetNum" : "1",
"packetItems" : [
{
"packetItemNum" : "Bc89",
"packetItemQty" : "1",
"packetItemCode" : "8",
},
{
"packetItemNum" : "Bc90",
"packetItemQty" : "3",
"packetItemCode" : "6",
},
{
"packetItemNum" : "Bc87",
"packetItemQty" : "3",
"packetItemCode" : "8",
}
]
}
]
}
我的要求是在不破坏结构的情况下过滤 packetItemCode 为 6 的元素
所需输出:
{
"_id" : "236165301",
"boxID" : "431414",
"boxName" : "Test",
"packets" : [
{
"packetID" : "635665346",
"packetQty" : "5",
"packetNum" : "1",
"packetItems" : [
{
"packetItemNum" : "Ab89",
"packetItemQty" : "1",
"packetItemCode" : "6",
},
{
"packetItemNum" : "Ab90",
"packetItemQty" : "3",
"packetItemCode" : "6",
}
]
},
{
"packetID" : "635665380",
"packetQty" : "6",
"packetNum" : "1",
"packetItems" : [
{
"packetItemNum" : "Bc90",
"packetItemQty" : "3",
"packetItemCode" : "6",
}
]
}
]
}
我尝试了什么:
db.getCollection('PacketData').aggregate([
{ "$match" : { "_id":"236165301" } },
{ "$unwind" : "$packets" },
{ "$unwind" : "$packets.packetItems" },
{ "$match" : { "packets.packetItems.packetItemCode" : "6" }}
])
但我无法编写组/项目声明来获得所需的结构输出。 你能帮忙吗
【问题讨论】:
-
使用
$redact运算符,如下所述。您也可以查看:stackoverflow.com/questions/49611773/…
标签: mongodb mongodb-query aggregation-framework