没有与嵌套的数组文件,只是想通过整理收集客户ID,然后productList.productId然后productList.itemList.id升序排列。MongoDb版本是3.0.14。
到目前为止,我已经尝试过了,查询未按预期对集合进行排序:
db.file_old.find({}, {
customerId: 1,
"productList.productId": 1,
"productList.itemList.id": 1
})
.sort({
customerId: 1,
productList: 1,
"productList.itemList": 1
})
并尝试聚合框架也像这样:
db.file_old.aggregate([
{"$unwind": "$productList"} ,
{"$sort": {"customerId": 1, "productList.productId": 1}}
])
对于两个字段,它工作正常,但是如果尝试添加“ productList.itemList.id”则不起作用,如下所示:
db.file_old.aggregate([
{"$unwind": "$productList"} ,
{"$sort": {"customerId": 1, "productList.productId": 1, "productList.itemList.id": 1}}
])
集合结构:
{
"_id" : ObjectId("5f33cc2a1e84082968132324"),
"customerId" : 2196,
"productList" : [
{
"productId" : 7531,
"itemList" : [
{
"id" : 144
},
{
"id" : 145
}
]
},
{
"productId" : 7534,
"itemList" : [
{
"id" : 1244
},
{
"id" : 1243
},
{
"id" : 1245
},
{
"id" : 1242
}
]
}
]
},{
"_id" : ObjectId("5f33cc2a1e84082968132326"),
"customerId" : 2201,
"productList" : [
{
"productId" : 101201,
"itemList" : [
{
"id" : 863
},
{
"id" : 865
},
{
"id" : 862
}
]
},
{
"productId" : 7537,
"itemList" : [
{
"id" : 982
},
{
"id" : 1002
},
{
"id" : 896
}
]
}
]
}
您无法直接对数组进行排序,首先需要展开(deconstruct),然后将应用排序,让我们一步一步看一下,
- 产品列表
- 解构数组($ unwind)
- itemList
- 解构数组($ unwind)
- 按ID排序($ sort)
- 重建数组($ group)
- 按productId排序($ sort)
- 重建productList($ group)
- 按customerId排序($ sort)
$unwind
解构productList
数组db.collection.aggregate([
{ $unwind: "$productList" },
$unwind
解构productList.itemList
数组 { $unwind: "$productList.itemList" },
$sort
通过productList.itemList.id
升序 { $sort: { "productList.itemList.id": 1 } },
$group
通过所有3个主要级别的ID并重新构建itemList
数组 {
$group: {
_id: {
_id: "$_id",
customerId: "$customerId",
productId: "$productList.productId"
},
itemList: { $push: "$productList.itemList" }
}
},
$sort
通过productId
升序 { $sort: { "_id.productId": 1 } },
$group
通过主要的2级ID并重新构建productList
数组 {
$group: {
_id: {
_id: "$_id._id",
customerId: "$_id.customerId"
},
productList: {
$push: {
productId: "$_id.productId",
itemList: "$itemList"
}
}
}
},
$project
显示必填字段 {
$project: {
_id: "$_id._id",
customerId: "$_id.customerId",
productList: 1
}
},
$sort
按customerId
编号 { $sort: { customerId: 1 } }
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句