2017-01-16 60 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});