本文介绍了MongoDB 获取子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 MongoDB 中的文档中检索子文档.我有以下文件:
I would like to retrieve a sub document from a document in MongoDB. I have the following document:
{ "_id" : "10000", "password" : "password1", "name" : "customer1", "enabled" : true, "channels" : [ { "id" : "10000-1", "name" : "cust1chan1", "enabled" : true }, { "id" : "10000-2", "name" : "cust1chan2", "enabled" : true } ] }我想要的结果是:
{ "id" : "10000-1", "name" : "cust1chan1", "enabled" : true }但是,到目前为止我能做的最好的事情是使用以下查询:
However, the best I can do so far is using the following query:
db.customer.find({"channels.id" : "10000-1"}, {"channels.$" : 1, "_id" : 0})但这给了我以下结果:
{ "channels" : [ { "id" : "10000-1", "name" : "cust1chan1", "enabled" : true } ] }有谁知道是否可以编写一个查询来给出我想要的结果?任何帮助将不胜感激.
Does anyone know if it is possible to write a query that will give me my desired result? Any help would be much appreciated.
推荐答案您可以使用聚合框架来实现.查询将类似于:
You can do it with Aggregation Framework. Query will be something like :
db.customer.aggregate([ {$unwind : "$channels"}, {$match : {"channels.id" : "10000-1"}}, {$project : {_id : 0, id : "$channels.id", name : "$channels.name", enabled : "$channels.enabled"}} ])更多推荐
MongoDB 获取子文档
发布评论