简体   繁体   中英

How to conditionally add a field based on match a field with an array Mongo

I'm trying to create a pipeline to add a field based in a condition:

I have a field called helpful which is an array that will contain a list of id's, what I want to do is add a field depending if a given ID is insided that array

an example of the data structure may be this:

    {
    helpful: [ 5ecd62230a180f0017dc5342 ],       
    verifiedPurchase: false,
    _id: 5f789010e07e4033342c7307,
    title: 'text',
    body: 'text',      
    rating: 3,
    user: {
      _id: 5ecd62230a180f0017dc5342,
      name: 'store11',
      picture: 'pictureurl'
    },
    replies: [],
    updatedAt: 2020-10-03T18:04:48.026Z,
    createdAt: 2020-10-03T14:52:00.410Z,
    helpfulCount: 1,
    helpfulForMe: false
  },

I already tried with this pipeline

{
            $addFields:{
                helpfulForMe: {
                    $cond: {
                        if: {"$in":[user, "$helpful"] } ,
                        then: true,
                        else: false,
                    }
                }
            }
        },

and this one

"$addFields": {
                "helpfulForMe" : {
                    "$in":[ 
                        ['5ecd62230a180f0017dc5342'], "$helpful"
                    ] 
                } 
            } 
        },

but both returned false even when I set a matching ID

I hope to get a good fix from you guys. Thanks

You can try if your input is array of ids,

  • $reduce to iterate loop of helpful array and check condition if id in user array then return true otherwise false
let user = ["5ecd62230a180f0017dc5342"];

  {
    $addFields: {
      helpfulForMe: {
        $reduce: {
          input: "$helpful",
          initialValue: false,
          in: {
            $cond: [{ $in: ["$$this", user] }, true, "$$value"]
          }
        }
      }
    }
  }

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM