MongoDB获取子文档

编程入门 行业动态 更新时间:2024-10-18 03:28:57
本文介绍了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.

推荐答案

您可以使用Aggregation Framework做到这一点.查询将类似于:

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获取子文档

本文发布于:2023-11-22 13:35:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!