如何基于mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?
我想从聚合映射操作符内部在函数级别设置一个变量。这是我到目前为止所拥有的一个片段如何基于mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?,mongodb,mongoose,mongodb-query,aggregation-framework,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我想从聚合映射操作符内部在函数级别设置一个变量。这是我到目前为止所拥有的一个片段 $project: { collectionId: 1, name: 1, description: 1, image: 1, created: 1, updated: 1, isPresent: "no", "products": { $map: { "input": "$products", as: "product", in: {
$project: {
collectionId: 1,
name: 1,
description: 1,
image: 1,
created: 1,
updated: 1,
isPresent: "no",
"products": {
$map: {
"input": "$products",
as: "product",
in: {
"title": "$$product.name",
"imageUrl": "$$product.mainImage",
"productId": "$$product.productId",
"$isPresent": "yes"
}
}
},
total: {
$size: "$products"
},
userId: "$user.userId",
userName: "$user.name",
}
我想根据条件在中的map操作符中将isPresent节点值设置为yes。目前,我一直把它保持在“是”。但这不起作用
操作方法是什么?您可以使用和运算符:
db.collection.aggregate([
/** `$products.productId` gives an array of 'productId''s from products array */
{
$addFields: { isPresent: { $cond: [ { $in: [ 2, "$products.productId" ] }, "Yes", "No" ] } }
}
])
测试:
注意:
当我们使用$in
时,每个文档都必须有产品
数组,否则$in
将出错,如果存在任何此类情况,您需要为没有产品
数组的文档设置跳过条件。您可以使用和运算符:
db.collection.aggregate([
/** `$products.productId` gives an array of 'productId''s from products array */
{
$addFields: { isPresent: { $cond: [ { $in: [ 2, "$products.productId" ] }, "Yes", "No" ] } }
}
])
测试:
注意:
当我们使用
$in
时,每个文档都必须有产品
数组,否则$in
将出错,如果存在任何此类情况,您需要为那些没有产品
阵列的文档设置跳过的条件。您希望在产品
阵列上检查的条件是什么?也许更好地解释一下什么情况下产品使父字段isPresent:“Yes”
我有一个名为productId的局部变量。。。我正在检查productId是否等于products数组中的任何productId。既有isPresent
又有$isPresent
,您指的是哪一个?您想检查products
数组的条件是什么?也许更好地解释一下什么情况下产品使父字段isPresent:“Yes”
我有一个名为productId的局部变量。。。我正在检查productId是否等于products数组中的任何productId。有isPresent
和$isPresent
,您指的是哪一个?