Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

mongodb query with $type operator doesn't work

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.

Upvotes: 7

Views: 1824

Answers (3)

Robert Stam
Robert Stam

Reputation: 12187

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 }})

Upvotes: 8

user2665694
user2665694

Reputation:

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...

Upvotes: 7

Andrew Orsich
Andrew Orsich

Reputation: 53685

It sound like a bug, i've tried run { "Array" : { $type : 4 } } from mongovue and it's also does not work for me. Going to check in mongoshell...

But if you want to know all nested array with at least one item you can do it like this:

db.users.find( { "LedgerBook.0.AccountId" : { $exists : true } })

Update: Following code also return nothing in mongoshell, so i guess it's bug..

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

Upvotes: 2

Related Questions