3

I have this entity in DB

{
    "_id" : ObjectId("XXX"),
    "Bets" : [ 
        {
            "IsPublic" : false
        }, 
        {
            "IsPublic" : false
        }
    ]
}

And I want to update all fileds IsPublic in nested documents. I have this query which works perfectly:

db.getCollection('bets').update({"_id": ObjectId("XXX")}, {$set : { "Bets.$[].IsPublic" : true }})

I want to write the same query with C# driver and I would prefer strongly typed query, something like this:

var filter = Builders<TrackerBet>.Filter.Eq(b => b.Id, "XXX");
var update = Builders<TrackerBet>.Update.Set(b => b.Bets[-1].IsPublic, true);
var result = mongoDb.Bets.UpdateOneAsync(filter, update).Result; 

But it doesn't work. If I give up strongly typed query it works:

var update = Builders<TrackerBet>.Update.Set("Bets.$[].IsPublic", true); 

Is it even possible to achieve a strongly-typed query? I thought that b.Bets[-1].IsPublic should do the trick, but I get the error The positional operator did not find the match needed from the query.

1 Answer 1

1

i'm not aware of any built-in way to get this done using the official driver. i've written a static utility class that returns string paths for supplied lambda expressions. with it you can eliminate the hard-coded string like so:

    var path = Prop.PosAll<TrackerBet>(t => t.Bets[0].IsPublic);
    var update = Builders<TrackerBet>.Update.Set(path, true);

here's more info on all the methods of the static class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.