node.js - 如何在 mongodb 3.2 中从集合中添加多个文档
问题描述
如何在一个数组中获取所有“产品”详细信息,在一个array.im
使用mongodb 3.2
版本中获取所有“cartItems”
getCartProducts: (userId) => {
return new Promise(async (resolve, reject) => {
let cartItems = await db.get().collection(collection.CART_COLLECTION).aggregate([
{
$unwind: "$products",
},
{
$lookup: {
from: collection.PRODUCT_COLLECTION,
localField: "products",
foreignField: "_id",
as: "cartItems"
}
},
{
$match: {
"product": { $ne: [] }
}
}
]).toArray()
resolve(cartItems)
})
}
这是我得到的当前输出
[
{
_id: 5f9ff4b1183ac302703b28b1,
user: 5f8fcdd5687bf506e44c9b4a,
products: 5f845d073340762378ba1522,
cartItems: [ [Object] ]
},
{
_id: 5f9ff4b1183ac302703b28b1,
user: 5f8fcdd5687bf506e44c9b4a,
products: 5f9b94d1ab78c11b142646cb,
cartItems: [ [Object] ]
},
{
_id: 5f9ff4b1183ac302703b28b1,
user: 5f8fcdd5687bf506e44c9b4a,
products: 5f9b953bab78c11b142646cd,
cartItems: [ [Object] ]
}
]
这是我需要的我想要的输出。我在用着 mongodb 3.2
[
{
_id: 5f9ff4b1183ac302703b28b1,
user: 5f8fcdd5687bf506e44c9b4a,
products:[ 5f845d073340762378ba1522,5f9b94d1ab78c11b142646cb,5f9b953bab78c11b142646cd ]
cartItems: [ [Object],[Object],[Object] ]
}
]
解决方案
添加这个阶段:
{
$group: {
"_id": "$_id",
user: {
"$first": "$user"
},
cartItems: {
$push: {
$arrayElemAt: [
"$cartItems",
0
]
}
},
products: {
$push: "$products"
}
}
}
推荐阅读
- java - 为什么我们发送给 sendgrid SMTP 的电子邮件会收到“Invalid SMTPAPI Header”错误?
- excel - 有没有办法在 tableau 中为工作表和仪表板创建模板?
- python - 如何记录 django 视图
- python - 如何在不打开 GUI 的情况下调用 plt.subplots()?
- go - 大摇大摆的一代正在忽略 SecurityDefiniton
- python - Keras Cnn 模型不会提高准确性
- oracle - DBMS_SCHEDULER.CREATE_JOB 返回“未知命令”
- ocaml - ReScript 中的无限列表/流
- asp.net-mvc - MVC 表单需要基于选择
- mysql - 从 MySQL 中的日期列获取每月计数