如何解决在猫鼬中添加查找后在$ project中添加剩余文件
我正在从Order模式中的_id执行$ lookup,并且按预期方式工作。但是在$project
中,如何添加剩余密钥。我在下面添加了我的代码。
产品系列:
{
"_id": "54759eb3c090d83494e2d804","product_name": "sample product","image": "default.png","price": 55,"discount": 5,}
订单列表集合
{
"user_name": "sample1","product_list":[
{
"product_id": "54759eb3c090d83494e2d804"
"quantity": 5
}
]
}
查找
[
{
from: 'product',localField: 'product_list.product_id',foreignField: '_id',as: 'product_list.product_id',model: 'ProductModel',},],
$ Project
{
user_name: true,product_list: {
$map: {
input: '$product_list.product_id',as: 'product',in: {
product_name: '$$product.product_name',}
当前结果:
{
"user_name": "sample1","product_list":[
"product_id":{
"product_name": "sample product"
}
]
}
在当前结果中,数量字段丢失。如何添加$project
?预期结果如下所示
预期结果:
{
"user_name": "sample1","product_list":[
{
"product_id": {
"product_name": "sample product"
}
"quantity": 5
}
]
}
解决方法
您需要在$unwind
之前执行$lookup
,因为它不能直接在数组字段中工作,并且这里在$ project中不需要$ map,
- $unwind
product_list
解构数组
db.order.aggregate([
{ $unwind: "$product_list" },
- $lookup with pipeline,这将允许在查找中使用管道,此处
$project
到必填字段
{
$lookup: {
from: "product",as: "product_list.product_id",let: { product_id: "$product_list.product_id" },pipeline: [
{
$match: {
$expr: { $eq: ["$$product_id","$_id"] }
}
},{
$project: {
_id: 0,product_name: 1
}
}
]
}
},
-
$unwind
和路径product_list.product_id
,因为您需要将其作为对象
{ $unwind: { path: "$product_list.product_id" } },
-
通过
- $group重新构建您的
product_list
数组
_id
的 {
$group: {
_id: "$_id",user_name: { $first: "$user_name" },product_list: { $push: "$product_list" }
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。