3

If $myDogsName is in the array dogNamesOfWinnersArray then myDogWins should be true if its not in the array it should be false.

Is this even possible?

    db.collection.aggregate([
        {
            $addFields: { myDogWins: { $myDogsName: [ "$dogNamesOfWinnersArray", [] ] } }
        }
    ])

the array looks like

dogNamesOfWinnersArray: [
        {
            "name" : "jake", 
            "age" : 6, 
            "breed" : "Bulldog", 
            ...
        },
        {
            "name" : "fred", 
            "age" : 8, 
            "breed" : "Bulldog",
            ... 
        },

    ]

$myDogsName is jake so I expect myDogWins to be true

2 Answers 2

3

The $in operator is what you need.

{
  "$addFields": {
    "myDogWins": {
      "$in": [
        "$myDogsName",
        "$dogNamesOfWinnersArray.name"
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

$myDogsName is just a string, $dogNamesOfWinnersArray is an array and the name can be found at $dogNamesOfWinnersArray.name
If I understand, the array elements are subdocuments. Is that correct?
I updated my question for clarity, how do I add name on the end of dogNamesOfWinnersArray
I've tried to run it but I get no data back at all, I feel that $dogNamesOfWinnersArray.name needs to be somthing like $dogNamesOfWinnersArray[x].name where x is the iterator?
No indexing. demo
0
db.dogs.save( { _id: 1, name: "jake" } )
db.dogs.save( { _id: 2, name: "jake2" } )

db.dogs.aggregate( [
  { 
      $addFields: { 
          dogNamesOfWinnersArray: { 
              $concatArrays: [ [ ], dogNamesOfWinnersArray ] 
          } 
      } 
  },
  { 
      $addFields: { 
          myDogWins: { $in: [ "$name", "$dogNamesOfWinnersArray.name" ] } 
      } 
  },
  { 
      $project: { dogNamesOfWinnersArray: 0 } 
  }
] )

The output:

{ "_id" : 1, "name" : "jake", "myDogWins" : true }
{ "_id" : 2, "name" : "jake2", "myDogWins" : false }

Comments

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.