Home > Enterprise >  MongoDB $elemMatch comparison to field in same document
MongoDB $elemMatch comparison to field in same document

Time:12-03

I'm wanting to create an aggregation step to match documents where the value of a field in a document exists within an array in the same document.

In a very worked example (note this is very simplified; this will be fitting into a larger existing pipeline), given documents:

{
    "_id":{"$oid":"61a9085af9733d0274c41990"},
    "myArray":[
        {"$oid":"61a9085af9733d0274c41991"},
        {"$oid":"61a9085af9733d0274c41992"},
        {"$oid":"61a9085af9733d0274c41993"}
    ],
    "myField":{"$oid":"61a9085af9733d0274c41991"}   // < In 'myArray' collection
}

and

{
    "_id":{"$oid":"61a9085af9733d0274c41990"},
    "myArray":[
        {"$oid":"61a9085af9733d0274c41991"},
        {"$oid":"61a9085af9733d0274c41992"},
        {"$oid":"61a9085af9733d0274c41993"}
    ],
    "myField":{"$oid":"61a9085af9733d0274c41994"}   // < Not in 'myArray' collection
}

I want to match the first one because the value of myField exists in the collection, but not the second document.

It feels like this should be a really simple $elemMatch operation with an $eq operator, but I can't make it work and every example I've found uses literals. What I've got currently is below, and I've tried with various combinations of quotes and dollar signs round myField.

[{
    $match: {
        myArray: {
            $elemMatch: {
                $eq: '$this.myField'
            }
        }
    }
}]

Am I doing something very obviously wrong? Is it not possible to use the value of a field in the same document with an $eq?

Hoping that someone can come along and point out where I'm being stupid :)

Thanks

CodePudding user response:

You can simply do a $in in an aggregation pipeline.

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$in": [
          "$myField",
          "$myArray"
        ]
      }
    }
  }
])

Here is the Mongo playground for your reference.

  • Related