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
CodePudding user response:
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
})
CodePudding user response:
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.