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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With