简体   繁体   English

用于查找对象类型的 Mongo db 查询

[英]Mongo db query for finding object type

I've 1000's of users and user data looks like the below.我有 1000 个用户,用户数据如下所示。 Some users have the devices as [{some data}] (array), some users have devices as {some data} , and some users have devices as empty [] .一些用户将设备设为[{some data}] (数组),一些用户将设备设为{some data} ,而一些用户将设备设为空[]

I need mongodb query to find the userslist with devices {some data} .我需要 mongodb 查询来查找带有设备{some data} Here is the sample of my users 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" : [] }

You can use $type operator like this您可以像这样使用$type运算符

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

or要么

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

Update :更新

Try one of below query as per your requirement (remove empty objects or keep 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:{}}} );

Check this screenshot:检查此屏幕截图:

在此处输入图片说明

在此处输入图片说明

Moreover, please note that you have duplicate keys ( _id ) in your data set which means those data sets are not inserted into your DB.此外,请注意您的数据集中有重复的键 ( _id ),这意味着这些数据集不会插入到您的数据库中。 So query will obviously won't give proper results.所以查询显然不会给出正确的结果。

Edit :编辑

OP removed duplicate keys from data set. OP 从数据集中删除了重复的键。

You can use $type operator.您可以使用$type运算符。

Find more detail on this link https://docs.mongodb.com/manual/reference/operator/query/type/在此链接上查找更多详细信息https://docs.mongodb.com/manual/reference/operator/query/type/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM