我需要这个查询的帮助。我怎么能找到一个子集?
收集客户
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
答案 0 :(得分: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")
}
}