mongodb 获取字段总和后添加条件
mongodb add condition after get sum of fileds
我在 mongo 数据库中有两个 table,如下所示
标签库存:
id
count
productId
0
10
0
1
0
1
2
4
0
3
0
1
table 个产品:
id
title
inventoryIds
0
test
[0,2]
1
test 1
[1,3]
我想为具有此条件的 table 产品编写查询 ==>
如果一种产品的库存计数总和 table 大于零 return 产品中具有此条件的所有数据 table
else return 产品中的所有数据
我想要的输出:
产品
id
title
inventoryIds
0
test
[0,2]
因为 productId = 0 的库存数量为 14,而 productId = 1 的库存数量为零!
谢谢你的帮助
这是 return documents 从 products
collection 给定你的条件和例子的一种方法。
db.products.aggregate([
{
"$lookup": {
"from": "inventories",
"localField": "inventories",
"foreignField": "productId",
"pipeline": [
{
"$group": {
"_id": null,
"sum": {
"$sum": "$count"
}
}
}
],
"as": "inventorySum"
}
},
{
"$match": {
"inventorySum.sum": {
"$gt": 0
}
}
},
{
"$unset": [
"_id",
"inventorySum"
]
}
])
在 mongoplayground.net 上试用。
结果:
[
{
"id": 0,
"inventories": [
0,
2
],
"title": "test"
}
]
我在 mongo 数据库中有两个 table,如下所示
标签库存:
id | count | productId |
---|---|---|
0 | 10 | 0 |
1 | 0 | 1 |
2 | 4 | 0 |
3 | 0 | 1 |
table 个产品:
id | title | inventoryIds |
---|---|---|
0 | test | [0,2] |
1 | test 1 | [1,3] |
我想为具有此条件的 table 产品编写查询 ==> 如果一种产品的库存计数总和 table 大于零 return 产品中具有此条件的所有数据 table else return 产品中的所有数据
我想要的输出:
产品
id | title | inventoryIds |
---|---|---|
0 | test | [0,2] |
因为 productId = 0 的库存数量为 14,而 productId = 1 的库存数量为零!
谢谢你的帮助
这是 return documents 从 products
collection 给定你的条件和例子的一种方法。
db.products.aggregate([
{
"$lookup": {
"from": "inventories",
"localField": "inventories",
"foreignField": "productId",
"pipeline": [
{
"$group": {
"_id": null,
"sum": {
"$sum": "$count"
}
}
}
],
"as": "inventorySum"
}
},
{
"$match": {
"inventorySum.sum": {
"$gt": 0
}
}
},
{
"$unset": [
"_id",
"inventorySum"
]
}
])
在 mongoplayground.net 上试用。
结果:
[
{
"id": 0,
"inventories": [
0,
2
],
"title": "test"
}
]