如何通过.net mongoDb驱动程序通过嵌套属性在mongoDb中获取文档 [英] How to get a document in mongoDb via a nested property through .net mongoDb driver

查看:68
本文介绍了如何通过.net mongoDb驱动程序通过嵌套属性在mongoDb中获取文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在某些收藏夹中有以下文件

Suppose i have following document in some collection

   [{
            "name": "Man1",            
            "Childrens": [
                 {
                     "name": "Children 1",
                     "age": "12"
                 },
                 {
                     "name": "Children 2",
                     "age": "18"
                 },
             ]
        },
{
            "name": "Man1",            
            "Childrens": [
                 {
                     "name": "Children 3",
                     "age": "12"
                 },
                 {
                     "name": "Children 4",
                     "age": "18"
                 },
             ]
        }
]

我想获得其中一个孩子的名字是"Children 1"的文件

i want to get the document where name of one of the children is "Children 1"

我想通过.net mongo驱动程序实现此目标

I want to achieve this via .net mongo driver

var bQuery = String.Format("{{ '{0}':'{1}' }}","Childrens.name","Children 1");
var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bQuery);
result = await db.GetCollection<T>(collectionName).Find<T>(filter).ToListAsync(); 

但此返回空列表 我好像在哪里

but this return empty list where as if i do

var bQuery = String.Format("{{ '{0}':'{1}' }}","name","Man1");

有效

所以当我们通过嵌套属性搜索时,我无法使其工作

so i am not able to make it work when we search via nested property

推荐答案

请尝试使用以下代码,并且我已经成功测试:

Please try to use below code and i have tested successfully:

{ "Childrens": { $elemMatch: { "name": "Children 1"} } }

您的代码应为:

var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ \"Childrens\": { $elemMatch: { \"name\": \"Children 1\"} } }");
result = await db.GetCollection<T>(collectionName).Find<T>(filter).ToListAsync(); 

这篇关于如何通过.net mongoDb驱动程序通过嵌套属性在mongoDb中获取文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆