2017-05-05 39 views
0

我有一個文件在蒙戈DB具有以下結構:

{ 
    "username" : "John Doe", 
    "userdocument" : "1026254745", 
    "user_id" : "6QH70tZrPbTDvqmOtUCcT9", 
    "createAt" : ISODate("2017-03-22T22:01:15.808Z"), 
    "network_clients" : [ 
     { 
      "client_id" : "6XvzpJ2IwnVT66pEkKU7E3", 
      "_id" : ObjectId("58d2f47dc9a288179cecb996"), 
      "usertype" : "client" 
     }, 
     { 
      "client_id" : "07nPfV5TEH1qTLDBK2xIMe", 
      "_id" : ObjectId("58d321aa26417b20f34bc7e7"), 
      "usertype" : "client" 
     }, 
     { 
      "client_id" : "3b45WntXG6KMX12qSEyMGc", 
      "_id" : ObjectId("590baf16ea97a217e4834370"), 
      "usertype" : "supplier" 
     } 
    ], 
    "useravatar" : "https://pos-lisa.s3.amazonaws.com/useravatar-1493859018209.jpg", 
    "comments" : "", 
} 

我喜歡讓過濾器與「CLIENT_ID」和「 usertype「字段。我想下面MongoDB中與貓鼬:

User.aggregate({ $match: 
    { $and: 
     [ 
      { 'network_clients.client_id': clientId }, 
      { 'network_clients.usertype': userType } 
     ] 
    } 
}).sort({ username: 'ascending' }) 

在我的應用程序,用戶可以成爲我的一個客戶的供應商,同一用戶可以是其他的我的客戶的客戶,但與此實現,mongo總是給我的用戶,無論他是客戶端還是供應商,所以我的客戶端在「客戶端列表」和「供應商列表」中看到用戶

如何在內部陣列中製作過濾器這個文件?在提前謝謝

+0

的可能的複製(http://stackoverflow.com/questions/15117030/how-to-filter-array-in [如何與MongoDB的子文檔濾波器陣列] -subdocument-with-mongodb) – Veeram

回答

0

我不知道我跟隨你在什麼你想做什麼。但也許這是接近它:

User.aggregate({$project:{'username':1,'network_clients':1}}, 
{$unwind:'$network_clients'}, 
{$match:{'network_clients.client_id':clientId,'network_clients.usertype':userType}}, 
{$sort:{username:1}}) 
+0

你是對的!在這裏,規則是:不發送'謝謝你',但我發送給你100萬個! :) – maoooricio