Mongodb request with $ type operator not working

I use the following document outline:

//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 the query db.users.find({ "LedgerBook" : { "$type" : 4 } }).limit(50); , it returns nothing, but for the request db.users.find({ "LedgerBook" : { "$type" : 3 } }).limit(50); works well (return all documents that have LedgerBook items).

Why is this happening?

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

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

+6
source share
3 answers

When you request 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 request is:

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

actually means: find all documents in which at least one of the elements of the LedgerBook array itself is an array. Despite the fact that LedgerBook itself is an array, none of its elements exist, so no documents match the query.

If you just want to request documents that have a LedgerBook item, you can use:

 db.items.find({ LedgerBook : { $exists : true }}) 
+8
source

The $ type of the array is determined by the type of its first element. Call it a bug or function. There is some problem posted by JIRA ...

+6
source

It sounds like an error, I tried to run { "Array" : { $type : 4 } } from mongovue, and it doesn't work for me either. Gonna check in mongoshell ...

But if you want to know all nested arrays with at least one element, you can do it like this:

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

Update: The following code also does not return anything in mongoshell, so I assume this is an error.

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

Source: https://habr.com/ru/post/885512/


All Articles