MongoDB:如何循环字段以查找每个值?

我需要循环产品字段以查找产品集合并检查产品类别。如果 category 等于某个值,我将在当前文档中添加一个新字段。

这是我第一个文档的示例:

{
   _id:(objId),'products':[
    {productId:987678},{productId:3456765}
}

还有我的产品文档:

{_id:(objId),category:1,name:2}

如果类别正确,我使用 addField 将其添加到我的第一个文档中:

category:true;

我不知道如何做到这一点。任何人都可以帮助我吗?

mahate 回答:MongoDB:如何循环字段以查找每个值?

https://mongoplayground.net/p/_KeECXkJTfB ,这里我们在查找之前已展开产品,然后比较找到的类别,然后如果找到则将类别设置为 true。

db.product.aggregate([
  {
    "$unwind": "$products"
  },{
    "$lookup": {
      "from": "category","localField": "products.productId","foreignField": "_id","as": "inventory_docs"
    }
  },{
    "$unwind": {
      path: "$inventory_docs",preserveNullAndEmptyArrays: true
    }
  },{
    "$addFields": {
      "products.category": {
        $cond: {
          if: {
            "$gt": [
              {
                $strLenCP: {
                  "$toString": {
                    "$ifNull": [
                      "$inventory_docs.category",""
                    ]
                  }
                }
              },0
            ]
          },then: true,else: false
        }
      }
    }
  }
])
本文链接:https://www.f2er.com/52984.html

大家都在问