Jeff Garew
Jeff Garew

Reputation: 11

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>'

Upvotes: 0

Views: 242

Answers (1)

Jeff Garew
Jeff Garew

Reputation: 11

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

Upvotes: 1

Related Questions