0

I am new to mongodb and I need to retrieve documents where any of coordinate's value is null or empty. e.g if coordinates[0] or coordinates[1] is null.

{
"_id": ObjectId("58ef15dcccac183a18cd5c69"),
"submission_location": {
    "type": "Point",
    "coordinates": [73.0574529,
    33.711476]
}}


{
"_id": ObjectId("58ef1acaccac183918cd5c6a"),
"submission_location": {
    "type": "Point",
    "coordinates": []
}}

I have used aggregate method, but its not returning any result.

db.tasks_submission.aggregate([
    {
    "$unwind": "$submission_location"
    },
    {
    "$unwind": "$submission_location.coordinates.0",
    "$unwind": "$submission_location.coordinates.1"
    },
    {
    "$match": {
        $or :[{
        "submission_location.coordinates.0": 0
        },
        {
        "submission_location.coordinates.1": 0
        }] 

    }
}
]).pretty()
Developer
  • 63
  • 1
  • 3
  • That's not your actual document structure, since it's not actually valid. If anything the `[0]:73.0574529` is actually stored as a "string" as in `"[0]:73.0574529"`, because it is not possible to store it any other way. – Neil Lunn Aug 02 '17 at 06:56
  • Sorry about document structure, i didn't know how to write in correct json format here. – Developer Aug 02 '17 at 07:08
  • It's actually really simple. Open up the mongo shell that comes with your installation. Find a document, and copy and paste the content into the question here. That way we now "exactly" what the document looks like. – Neil Lunn Aug 02 '17 at 07:10
  • @NeilLunn i have updated document structure – Developer Aug 02 '17 at 07:25
  • That's better. Use `.find({ "submission_location.coordinates.0": { "$exists": false } })`. It's a little trick of "dot notation" where we ask if there is actually any data present at the first index position of the array. Where it is not, then the array is empty. Which should already be a question answered here. Also `.find({ "submission_location.coordinates": { "$size": 0 } })` does basically the same thing. The other is a bit more flexible to get used to though. – Neil Lunn Aug 02 '17 at 07:28
  • Duplicate of : [Query for documents where array size is greater than 1](https://stackoverflow.com/questions/7811163/query-for-documents-where-array-size-is-greater-than-1) – Neil Lunn Aug 02 '17 at 07:30
  • Thanks for your time @NeilLunn. It worked. – Developer Aug 02 '17 at 07:32

1 Answers1

0

https://docs.mongodb.com/v3.2/tutorial/query-for-null-fields/

Could be:

db.tasks_submission.find($or:[
    { submission_location.coordinates: null },
    { submission_location.coordinates.0: null },
    { submission_location.coordinates.1: null }
])
Sergej
  • 2,030
  • 1
  • 18
  • 28