skip to Main Content

I’m using MongoDb version 5.0.6.

I have this structure:

{
  "_id": ObjectId("60c7180d5ef87b4de490c56d"),
  "data": {
    "user": [
      {"country": "Netherlands", "originalCountry": "Denmark"},
      {"country": "France", "originalCountry": "Denmark"},
    ]
  },
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
  "data": {
    "user": [
      {"country": "ITALIE", "originalCountry": "ITALIE"},
      {"country": "France", "originalCountry": "France"},
    ]
  }
},
"_id": ObjectId("60c7180d5ef87b4de490c56d"),
  "data": {
    "user": [
      {"country": "UK", "originalCountry": "CANADA"},
      {"country": "France", "originalCountry": "France"},
    ]
  }
}

I wish to find only the documents that have country equal to supplierCountryin this case:

"_id": ObjectId("60c7180d5ef87b4de490c56d"),
  "data": {
    "user": [
      {"country": "ITALIE", "originalCountry": "ITALIE"},
      {"country": "France", "originalCountry": "France"},
    ]
  }
}

I have tried with this query

db.collection.find({
  "data.user": {
    $elemMatch: {
      "country": {
        $ne: "$data.user.originalCountry"
      }
    }
  }
})

but the result is not right.

2

Answers


  1. By using $map, you can project the data.user array to an array of boolean by comparing the 2 country fields. Then, use $allElementsTrue to find documents that have all array entries true. (i.e. all array entries are having same country)

    db.collection.find({
      "$expr": {
        "$allElementsTrue": {
          "$map": {
            "input": "$data.user",
            "as": "u",
            "in": {
              $eq: [
                "$$u.country",
                "$$u.originalCountry"
              ]
            }
          }
        }
      }
    })
    

    Mongo Playground

    Login or Signup to reply.
  2. You can use aggregation. This will compare the 2 values country and originalCountry in the same user object array and return those documents

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $eq: [
              "$data.user.country",
              "$data.user.originalCountry"
            ]
          }
        }
      }
    ])
    

    Mongo Playground: https://mongoplayground.net/p/OhJXK7CC3HX

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search