A mongo db request is required to search for an object type

I have 1000 users and user data is as follows. Some users have devices as [{some data}] (array), some users have devices as {some data} , and some users have devices as empty [] .

I need a mongodb query to find a list of users with {some data} devices. Below is an example of my user data.

 { "_id" : ObjectId("56fe07bab95708fa18d45ac4"), "username" : "abcd", "devices" : [] }, { "_id" : ObjectId("56fe07bab95708fa18d45df7"), "username" : "efgh", "devices" : [ { "_id" : ObjectId("5827804ef659a60400e12fcb"), "devicetype" : "web" } ], }, { "_id" : ObjectId("56fe07bab95708fa18d45ae8"), "username" : "efgh", "devices" : { "_id" : ObjectId("5951ea8b47abe300046ea26e"), "devicetype" : "web" } }, { "_id" : ObjectId("56fe07bab95708fa18d45b5b"), "username" : "ijkl", "devices" : [ { "_id" : ObjectId("59bd2317eeff3200049a2ba6"), "devicetype" : "ios" "devicetoken" : "1abffaa4419d498b48d0bf982" } ], }, { "_id" : ObjectId("56fe07bab95708fa18d46102"), "username" : "efgh", "devices" : { "_id" : ObjectId("58c433da28841d00040d3cdb"), "devicetype" : "web" } }, { "_id" : ObjectId("56fe07bab95708fa18d46177"), "username" : "efgh", "devices" : { "_id" : ObjectId("59d073d96974d20004a4bb9f"), "devicetype" : "web" } }, { "_id" : ObjectId("56fe07bab95708fa18d456c9"), "username" : "ijkl", "devices" : [ { "_id" : ObjectId("59b93dd2e6673c00044cca49"), "devicetype" : "ios" "devicetoken" : "1abffaa4419d498b48d0bf982" } ], }, { "_id" : ObjectId("56fe07bab95708fa18d456f4"), "username" : "abcd", "devices" : [] } 
+5
source share
3 answers

Usage can use $type like this

db.collection.find( { "devices" : { $type : "object" } } );

or

db.collection.find({ "devices": { $not: { $type: "array" } }})

+2
source

Update

Try one of the following queries according to your requirement (delete empty objects or save only empty objects):

 db.device.find( {$and:[ {devices:{ $type : "object" }},{devices:{$not: { $type: "array" }}}], devices:{$ne:{}}} ); db.device.find( {$and:[ {devices:{ $type : "object" }},{devices:{$not: { $type: "array" }}}], devices:{$eq:{}}} ); 

Install this screenshot: enter image description here enter image description here

Also, note that there are duplicate keys ( _id ) in your dataset, which means that these datasets are not inserted into your database. Thus, the query will obviously not yield the correct results.

Edit : OP removes duplicate keys from the dataset.

+2
source

You can use the $type operator.

Read more about this link https://docs.mongodb.com/manual/reference/operator/query/type/

+1
source

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


All Articles