[英]Mongoose | Find objects inside of an array, that each object has another array of objects to satisfy condition
I have a collection Shops .我有一个集合Shops 。 Each object in Shops collection has an array of
Item
objects called items
. Shops集合中的每个 object 都有一个名为
items
的Item
对象数组。
{
_id: ObjectId(...),
shopName: 'Ice cream Shop',
items: [
<Item>{
itemName: 'Chocolate IC',
availabilities: [
{
city: 'NY',
arrivals: [
{
price: 3.99,
quantityLeft: 0,
date: 'yesterday'
},
{
price: 3.99,
quantityLeft: 40,
date: 'today'
}
]
},
{
city: 'LA',
arrivals: []
}
]
},
<Item>{
itemName: 'Strawberry IC',
availabilities: [
{
city: 'NY',
arrivals: [
{
price: 3.99,
quantityLeft: 0,
date: 'yesterday'
},
]
}
]
},
],
},
... anotherShops
I want to get list of Item
objects which has overall quantityLeft more than 0 from a specific shop
.我想从特定
shop
获取总 quantityLeft 大于 0 的Item
对象列表。 I tried this code to get all items
with the name start with "Straw"
from a Shop with shopName
equal to 'Ice cream Shop'
:我尝试使用此代码从
shopName
等于'Ice cream Shop'
的商店中获取名称以"Straw"
开头的所有items
:
const items = await Shop.aggregate()
.match({
shopName: 'Ice cream Shop',
})
.project({
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$regexMatch: {
input: "$$item.itemName",
regex: `.*Straw.*`,
},
},
},
},
});
And it works.它有效。 But I don't know how to sum up all
quantityLeft
values inside availabilities
array of each item
, and return only that items
that has sum more than 0.但我不知道如何对每个
item
的availabilities
数组中的所有quantityLeft
值求和,并只返回总和大于 0 的items
。
availabilities
array can be an empty array [].availabilities
数组可以是空数组 []。
The
city
parameter also needs to be in condition.city
参数也需要符合条件。 For example, only Items that are in stock inNY
例如,只有
NY
有货的商品
I need this to get the list of items from a certain shop, and only the items that are still in stock.我需要这个来获取某家商店的商品清单,并且只有仍有库存的商品。 Pretty hard.
相当困难。
I came up with this solution.我想出了这个解决方案。 If you have a better solution, please post it.
如果您有更好的解决方案,请发布。
const shop = await GCShop.aggregate([
{
$match: {
shopName: 'Ice Cream Shop',
},
},
{
$unwind: "$items",
},
{
$unwind: "$items.availabilities",
},
{
$unwind: "$items.availabilities.arrivals",
},
{
$group: {
_id: "$items.id",
items_name: { $first: "$items.name" },
arrivals: {
$push: {
arrival_id: "$items.availabilities.arrivals.arrival_id",
price: "$items.availabilities.arrivals.price",
qtty: "$items.availabilities.arrivals.qtty",
},
},
totalQtty: { $sum: "$items.availabilities.arrivals.qtty" },
},
},
{
$project: {
offer_id: "$_id",
_id: 0,
offer_name: 1,
totalQtty: 1,
arrivals: 1,
},
},
{
$match: {
totalQtty: {
$gt: 0,
},
},
},
]).limit(20);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.