如果您执行aggregate 将unwind 您的数组,则不必循环遍历结果。看看那个查询:
db.device.aggregate([{
"$unwind": "$categories"
},{
"$unwind": "$categories.products"
}])
会将您的数组转换为 json 对象:
{ "_id" : "1", "name" : "list 1", "categories" : { "categoryId" : "201", "products" : { "productId" : "301", "name" : "product 1" } } }
{ "_id" : "1", "name" : "list 1", "categories" : { "categoryId" : "201", "products" : { "productId" : "302", "name" : "product 2" } } }
{ "_id" : "1", "name" : "list 1", "categories" : { "categoryId" : "202", "products" : { "productId" : "302", "name" : "product 2" } } }
{ "_id" : "1", "name" : "list 1", "categories" : { "categoryId" : "202", "products" : { "productId" : "304", "name" : "product 4" } } }
{ "_id" : "2", "name" : "list 2", "categories" : { "categoryId" : "201", "products" : { "productId" : "303", "name" : "product 3" } } }
{ "_id" : "2", "name" : "list 2", "categories" : { "categoryId" : "201", "products" : { "productId" : "304", "name" : "product 4" } } }
{ "_id" : "2", "name" : "list 2", "categories" : { "categoryId" : "202", "products" : { "productId" : "302", "name" : "product 2" } } }
{ "_id" : "2", "name" : "list 2", "categories" : { "categoryId" : "202", "products" : { "productId" : "304", "name" : "product 4" } } }
根据自己的喜好组合一些匹配项,即可轻松获得特定结果。以下将只为您提供包含特定 categories.categoryId 和 categories.products.productId 的记录:
db.device.aggregate([{
"$unwind": "$categories"
},{
"$unwind": "$categories.products"
}, {
$match: {
"categories.categoryId": "201",
"categories.products.productId": "301"
}
}])
给你:
{
"_id": "1",
"name": "list 1",
"categories": {
"categoryId": "201",
"products": {
"productId": "301",
"name": "product 1"
}
}
}
您可以添加$group 键以按_id 或其他任何方式分组。看https://docs.mongodb.com/manual/aggregation/
要删除子数组products 中的一项,也无需循环遍历结果,使用update 请求和pull,您可以在数组中准确找到您想要的内容并在一个请求中将其删除.
在以下请求中,我使用pull 和elemMatch 的结果定义的位置参数,因为您在另一个数组中有一个数组:
db.device.update({
'categories': {
'$elemMatch': {
categoryId: '201'
}
},
_id: '1'
}, {
$pull: {
'categories.$.products': {
'productId': '301'
}
}
});
上面的查询将只删除包含productId 301 的元素,用于categoryId 201 和元素匹配_id=1
查看https://docs.mongodb.com/manual/reference/operator/update/pull/