[英]MongoDB - Get an unique array from two queries
First of all sorry if the title does not reflect what I really need to do.首先抱歉,如果标题不能反映我真正需要做的事情。
Imagine a collection that represents what products sell which vendor.想象一个代表什么产品卖给哪个供应商的集合。 Let´s simplify like:
让我们简化如下:
{_id, productID, VendorID, Price, Stock}
For example, we could have:例如,我们可以:
{_id: 1 ,productID: 1, vendorID: A, price: 0, stock: 0},
{_id: 2 ,productID: 2, vendorID: A, price: 0, stock: 0},
{_id: 3 ,productID: 3, vendorID: A, price: 0, stock: 0},
{_id: 4 ,productID: 4, vendorID: A, price: 0, stock: 0},
{_id: 5 ,productID: 1, vendorID: B, price: 0, stock: 19},
{_id: 6 ,productID: 3, vendorID: B, price: 0, stock: 21}
The idea is that Vendor A is the Super Admin and the one who controls which products can be sold in the marketplace.这个想法是,供应商 A 是超级管理员,负责控制哪些产品可以在市场上销售。 That´s why all products sold by A have price = 0 and stock = 0.
这就是为什么 A 销售的所有产品的价格 = 0 且库存 = 0。
What I am trying to get within the same query is.我试图在同一个查询中得到的是。 When Vendor B is logged:
记录供应商 B 时:
The result would look like:结果将如下所示:
{_id: 2 ,productID: 2, vendorID: A, price: 0, stock: 0},
{_id: 4 ,productID: 4, vendorID: A, price: 0, stock: 0},
{_id: 5 ,productID: 1, vendorID: B, price: 0, stock: 19},
{_id: 6 ,productID: 3, vendorID: B, price: 0, stock: 21}
Do you have any idea how I can do it in a shot?你知道我怎么能一次完成吗?
I can do the filter in the frontend but I would prefer doing like this in order to avoid problems with pagination for example.我可以在前端进行过滤,但我更喜欢这样做,以避免例如分页问题。
If you are sure that all products sold by A
always have price = 0 and stock = 0, you can do the following trick:如果您确定
A
销售的所有产品的价格 = 0 且库存 = 0,则可以执行以下技巧:
db.collection.aggregate({
$match: {
vendorID: {
$in: [
"A",
"B"
]
}
}
},
{
$sort: {
productID: 1,
price: -1
}
},
{
"$group": {
"_id": "$productID",
"product": {
$first: "$$ROOT"
}
}
})
A
) and target vendor ( B
).A
) 和目标供应商 ( B
) 拥有的所有产品。productID
and by price in each group, so product sold by A
will be last one in each group productID
和按价格在每组中对产品进行分组,因此A
销售的产品将是每组中的最后一个A
will be matched only if no other products with same ID were sold).A
销售的产品)。 DB documents will be aggregated by $$ROOT
into product
field, so you can map them using:数据库文档将通过
$$ROOT
聚合到product
字段中,因此您可以使用 map 它们:
// (javascript)
const productDocuments = aggregationResult.map(row => row.product);
Notice: product sold by A
still can be extracted even if B
sold product with same ID in cases when B
's product also have price = 0.注意:如果
B
的产品也有 price = 0 的情况下,即使B
销售的产品具有相同的 ID,仍然可以提取A
销售的产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.