简体   繁体   中英

Need help accessing a nested object in mongo though C# driver

I'm trying to remove an object from an array, but I'm assuming this will be the same procedure for accessing nested objects for update as well.

Assuming my data looks like this

results myColl01 = {_id:1
                    a:100
                    b:[{aa:500,
                        bb:1000},
                       {aa:700,
                        bb:2000}]
                   }

I want to remove a doc from b where b.aa == 500

Here is what the C# code I'm using looks like:

int mc01_id = 1;
int mc01B_AA_val = 500;
IMongoQuery query = Query<MyColl01>.EQ(mc01=> mc01.Id, id);
IMongoUpdate update = Update<MyColl01>.Pull(mc01 => mc01.b,
                              Query<MyColl01_B>.EQ(mc01b => mc01b.aa, mc01B_AA_val));

WriteConcernResult updateResult =
this.MongoConnectionHandler.MongoCollection.Update(query, update);

I know it can be done by taking out the , but I want to avoid using literals in the query.

The returned error follows:

Argument 2: cannot convert from
'MongoDB.Driver.IMongoQuery' to
'System.Func<MongoDB.Driver.Builders.QueryBuilder<MyProject.MyColl01_B>,
       MongoDB.Driver.IMongoQuery>'

So I found the answer by accident elsewhere. To access the sub-class/document you will be pulling from you will need to use the builder.

IMongoUpdate update = Update<MyColl01>.Pull(mc01 => mc01.b,
                          builder => builder.EQ(b => b.aa, mc01B_AA_val));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM