kedoink
kedoink

Reputation: 101

MongoDB Only show equal fields when they exist

How do you only show those that exist?

This is my current code: db.collection.find({ $expr: {$eq: ["fieldA", "fieldB"]}, {"_id":0, "fieldC":1})

I have been trying things like the below but unsure of the correct syntax

db.collection.find({ $expr: {$eq: {$exists: ["fieldA", "fieldB"]}}, {"_id":0, "fieldC":1})

db.collection.find({ $expr: {$eq: ["fieldA": {$exists: true}, "fieldB": {$exists: true}]}}, {"_id":0, "fieldC":1})

Upvotes: 0

Views: 411

Answers (1)

R2D2
R2D2

Reputation: 10737

Maybe you are looking for this:

db.collection.aggregate([
{
 $match: {
    $and: [
      {
        "fieldA": {
          $exists: true
        }
      },
      {
        "fieldB": {
          $exists: true
        }
      },
      {
        $expr: {
           $eq: [
              "$fieldA",
              "$fieldB"
           ]
         }
       }
      ]
     }
    }
 ])

Explained: and:[ {exist(A)} ,{exist(B)} ,{A=B?} ]

playground

Upvotes: 1

Related Questions