开发者

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",开发者_Go百科
                ....
            },
            ... 
      ]

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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜