2017-01-16 61 views
0

我需要此查詢的幫助。我怎麼能找到一個子集?按ID查找mongo子集合

收集clientes

db.clientes.find({ 
    _id: ObjectId("587cc2d8704ae610d3741e6b") 
}); { 
    "_id": ObjectId("587cc2d8704ae610d3741e6b"), 
    "razonSocial": "CREXELL", 
    "cuit": "20-12121212-0", 
    "vsat": [{ 
     "CPA": 8682, 
     "IP": "149.126.35.61" 
    }, { 
     "CPA": 5500, 
     "IP": "149.126.36.109", 
     "_id": ObjectId("587cdb2af073f02a251361e8") 
    }, { 
     "CPA": 1234, 
     "IP": "1902312", 
     "_id": ObjectId("587d05fb930d504018ef8e01") 
    }], 
    "__v": 7 
} 

我需要得到類似如下:

{ 
      "CPA": 5500, 
      "IP": "149.126.36.109", 
      "_id": ObjectId("587cdb2af073f02a251361e8") 
     } 

感謝:d

回答

2

可以使用聚合來實現這一點,但你也需要知道_id你正在尋找子文檔數組。

db.clientes.aggregate([ 
    // Find the document matching the _id only 
    { $match: { "_id": ObjectId("587cc2d8704ae610d3741e6b") } }, 
    // Split all vsat array elements into separate documents 
    { $unwind: "$vsat" }, 
    // Match only the case where the _id matches 587cdb2af073f02a251361e8 
    { $match: { "vsat._id": ObjectId("587cdb2af073f02a251361e8") } }, 
    // Choose the elements we wish to return 
    { $project: { "vsat": 1, "_id": 0 } } 
]) 

結果:

{ 
    "vsat" : { 
     "CPA" : 5500, 
     "IP" : "149.126.36.109", 
     "_id" : ObjectId("587cdb2af073f02a251361e8") 
    } 
} 
+0

感謝您的回覆!查詢返回empy 'db.clientes.aggregate([{$ match:{「_id」:ObjectId(「587cc2d8704ae610d3741e6b」)}},{$ unwind:「$ vsat」},{$ match:{「 vsat._id「:ObjectId(」587cdb2af073f02a251361e8「)}},{$ project:{」vsat「:1,」_id「:0}}]); >' –

+0

嘗試一次添加一個管道的每個階段。第一這樣的: db.clientes.aggregate([ {$匹配:{ 「_id」:的ObjectId( 「587cc2d8704ae610d3741e6b」)}} ]) 然後此:db.clientes.aggregate([ {$匹配: {「_id」:ObjectId(「587cc2d8704ae610d3741e6b」)}} {$ unwind: – dyouberg

0

你可以嘗試定期查詢喜歡的東西下面。

使用elemMatch

db.clientes.find({"_id": ObjectId("587cc2d8704ae610d3741e6b")}, { "vsat": { $elemMatch: { "_id": ObjectId("587cdb2af073f02a251361e8") } } }); 

使用Positional操作

db.clientes.find({"_id": ObjectId("587cc2d8704ae610d3741e6b"), "vsat._id" : ObjectId("587cdb2af073f02a251361e8")}, { "vsat.$":1});