How to get a document in mongoDb via a nested prop

2019-07-24 17:15发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-07-24 17:47

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(); 
查看更多
登录 后发表回答