Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb query with $type operator doesn't work

Tags:

mongodb

I use following document schema:

//User Document
 {
     "_id": "0610457c-b25b-4e73-b859-11987a3fe271",
     "FirstName": "Some Name",
     "LastName": "surname",
     // it is array of ledger items
     "LedgerBook": [
            {
                "AccountId": "aadfgdf6319d3-1a12-4575-9776-c6653sdfg5c32527",
                "TransactionId": "ef98bbc4-3efb-46dc-b632-5adfgdfg1fcc378446",
                ....
            },
            ... 
      ]

and when I try to apply query db.users.find({ "LedgerBook" : { "$type" : 4 } }).limit(50); it returns nothing, but for query db.users.find({ "LedgerBook" : { "$type" : 3 } }).limit(50); works well(return all documents that has LedgerBook items).

Why does it happen?

type = 4 is Array and type = 3 is Object.

I want to get all documents thats have at least one LedgerBook item.

like image 740
Andrei Andrushkevich Avatar asked Apr 08 '11 13:04

Andrei Andrushkevich


2 Answers

When you query against an array the test is conceptually applied to each element of the array until it returns true for one of the elements, or until the end of the array is reached.

So the query:

db.items.find({ LedgerBook : { $type : 4 }})

actually means: find all documents where at least one of the items of the LedgerBook array is itself an array. Even though LedgerBook itself is an array, none of its elements are, so no documents match the query.

If you just want to query for documents that have a LedgerBook element you can use:

db.items.find({ LedgerBook : { $exists : true }})
like image 117
Robert Stam Avatar answered Oct 02 '22 13:10

Robert Stam


The $type of an array is defined through the type of its first item. Call it a bug or a feature. There is some issue posted to JIRA...

like image 33
Andreas Jung Avatar answered Oct 02 '22 14:10

Andreas Jung