簡體   English   中英

用於查找對象類型的 Mongo db 查詢

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM