javascript - 无论数组中的 ID 是否存在多次,如何获取由 ID 数组查询的文档
问题描述
我刚刚发现我可以在不使用循环的情况下在猫鼬中迭代 find()。通过做这个。
const arrOfIds = reqBody.items.map(item => item.productId);
Product.find({ '_id': { $in: arrOfIds }},(error, result)=>{
const productList = collect(result).toArray();
})
但是我的问题是,如果数组(arrOfIds)中存在不止一次的 id,则 find() 方法仅将其视为一个存在,因此这是不正确的,因为我想对这些产品的价格求和,重复或不是。
我之前的代码是使用 map() 循环 find() 然后计算总和但与其他代码复杂,我只想要使用这个更简单的方法。无论是否有重复,我都可以让它返回每个 ID 的文档吗?
解决方案
假设 arrOfIds 是 ["product1", "product4", "product3", "product1", "product1" ] 那么你可以使用下面的聚合请参考 https://mongoplayground.net/p/1DtTtZWCHaH
db.collection.aggregate([
{
"$match": {
_id: {
$in: [
"product1",
"product4",
"product3",
"product1",
"product1"
]
}
}
},
{
"$set": {
"totalPrice": {
"$function": {
"body": "function(arrOfIds,_id,price) {try { var total=0; arrOfIds.forEach((entry) => { if (entry=== _id){total= total+price;}})} catch (e) {row_number= 0;}return total;}",
"args": [
[
"product1",
"product4",
"product3",
"product1",
"product1"
],
"$_id",
"$price"
],
"lang": "js"
}
}
}
}
])
我们根据我们的数组匹配产品,然后我们根据出现的次数设置总价格,使用 set 通过实现函数来执行每个逻辑!它仍然是 foreach/loop 但在服务器端
推荐阅读
- performance - 超级账本 TPS
- angular - 当从父级发送相同的值时如何检测@input属性的变化
- utf-8 - UTF-8 如何表示字符?
- html - 仅使用 CSS 的彩虹文本动画
- reactjs - 转到另一个页面时,React Navigation V3 处理过渡和动画
- ajax - 使用ajax关闭模式后无法重新打开模式
- python - pandas resample dropna 不适用于所有列
- cesium - 如何获得用铯渲染的gltf纹理的状态
- javascript - 添加后缀跟随用户输入材料ui TextField
- reactjs - 如何从 React PWA 调用 HTTP 请求?