0

My mongodb document contains object CarData with several properties inside.

{
   _id: ...,
   Name: "",
   CarData: {
     carId: null,
     ownerName: "",
     ownerPhone: "",
     AdditionalInfo:{
       RefNr: ""
       validDoc: true
    }
   }
}

I know I can query the whole collection

{ "CarData": { $exists: true } }

but I don't know how to query whole collection with

CarData exists and is not null 
and ownerName != "" 
and AdditionalInfo exists and  != null 
and AdditionalInfo.validDoc == true

2 Answers 2

1

In mongo you don't need to check if the fields exist before checking internal properties. I think this should be enought for you. Playground

db.collection.find({
  "CarData.ownerName": {
    "$ne": ""
  },
  "CarData.AdditionalInfo.validDoc": true
})
Sign up to request clarification or add additional context in comments.

Comments

1

To get the documents as per your specification. you have to use aggregation provided by MongoDB. The query below will fulfill your requirements.

db.collection.aggregate([
  {
    $match: {
      "$and": [
        {
          CarData: {
            "$exists": true
          }
        },
        {
          CarData: {
            "$ne": null
          }
        },
        {
          "CarData.ownerName": {
            $ne: ""
          }
        },
        {
          $and: [
            {
              "CarData.AdditionalInfo": {
                "$exists": true
              }
            },
            {
              "CarData.AdditionalInfo": {
                "$ne": null
              }
            },
            {
              "CarData.AdditionalInfo.validDoc": true
            }
          ]
        }
      ]
    }
  }
])

The above query will give the list of documents with the matching condition.

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.