arraysmongodbmongodb-querydocuments

Querying for an object vs array


How do I query for an object vs an array of objects in a document?

I need to select all the documents that are like Dataset 2.

Dataset 1:

{
    'firstname' : 'John', 
    'lastname': 'Smith', 
    'assistance': [
        {'type': 'Food', 'amount': 20}
    ]
}

Dataset 2:

{
    'firstname' : 'John', 
    'lastname': 'Smith', 
    'assistance': {
        'type': 'Food', 
        'amount': 20
    }
}

Solution

  • db.foo.find( { "assistance" : { $type : 3 } } ); // 3 is bson type for object
    

    will return both the documents and

    db.foo.find( { "assistance" : { $type : 4 } } ); // 4 is bson type for object
    

    will return none of the two documents.

    This is becuase in mongodb, when querying on an array, the array elements are checked instead on the complete array.

    You can eliminate all elements where assistance is of type array by:

    db.foo.find({"assistance.0" : {$exists : false}})