How to get a document in mongoDb via a nested property through .net mongoDb driver

旧巷老猫 提交于 2019-12-24 17:06:52

问题


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"
                 },
             ]
        }
]

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

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");

it works

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


回答1:


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

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

And your code would be:

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


来源:https://stackoverflow.com/questions/50977712/how-to-get-a-document-in-mongodb-via-a-nested-property-through-net-mongodb-driv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!