1

I have a MongoDB with this structure:

enter image description here

Registration is an array & it's Object look like this:

{
        "_id" : ObjectId("5e844235ead49b7ff33962d3"), 
        "date" : "2-jul", 
        "firstname" : "John", 
        "lastname" : "Doe", 
        "email" : "[email protected]", 
        "education" : "University", 
        "gender" : "male", 
        "age" : "32", 
        "workshop" : [2,3,6]
}

And known looks like this:

"known" : [
        "[email protected]", 
        "[email protected]", 
        "[email protected]"
]

How can you check if registrations.email exists in known? If it exist how can you add a field to registrations: emailIsKnown: true or emailIsKnown: false?

I've tried different variations of filter, replaceRoot, lookUp with pipelines and mergeObject. But I can't seem to figure out how to only accomplish a minimum of comparing results or adding a field to the registrations object.

2
  • Is registrations an array of objects or an object ? Commented Apr 1, 2020 at 17:22
  • @whoami an array of objects Commented Apr 1, 2020 at 17:45

1 Answer 1

1

You can do that using aggregation-pipeline, try below query :

db.collection.aggregate([
  /** Re-create 'registration' array field */
  {
    $addFields: {
      registration: {
        $map: {
          input: "$registration", // Iterate on 'registration' array
          in: {
            $cond: [
              { $in: ["$$this.email", "$known"] }, // Check if current object's email exists in 'known' array
              { $mergeObjects: [{ emailIsKnown: true }, "$$this"] }, // If Yes, add new field with true to existing Object
              { $mergeObjects: [{ emailIsKnown: false }, "$$this"] } // If No, add new field with false to existing Object
            ]
          }
        }
      }
    }
  }
]);

Test : MongoDB-Playground

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks whoami, it's really nice to have an extended example like yours including the this keyword, map and a condition. I'm gonna have a lot of fun with this from now on forwards. Your solution worked instantly, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.