[英]Mongo db query for finding object type
我有 1000 个用户,用户数据如下所示。 一些用户将设备设为[{some data}]
(数组),一些用户将设备设为{some data}
,而一些用户将设备设为空[]
。
我需要 mongodb 查询来查找带有设备
{some 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" : [] }
您可以像这样使用$type
运算符
db.collection.find( { "devices" : { $type : "object" } } );
要么
db.collection.find({ "devices": { $not: { $type: "array" } }})
更新:
根据您的要求尝试以下查询之一(删除空对象或仅保留空对象):
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:{}}} );
检查此屏幕截图:
此外,请注意您的数据集中有重复的键 ( _id
),这意味着这些数据集不会插入到您的数据库中。 所以查询显然不会给出正确的结果。
编辑:
OP 从数据集中删除了重复的键。
您可以使用$type
运算符。
在此链接上查找更多详细信息https://docs.mongodb.com/manual/reference/operator/query/type/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.