简体   繁体   中英

MongoDB updateMany set a boolean field using equals

I have an IsDefault field in my model, and I want to set it to true for one document only and false for the others. Is this possible in a single query? I tried

{ $set: { IsDefault: {$eq: [_id, id ]}}}
 
{ $set: { IsDefault: { $cond: { if: { $eq: [$_id, id] }, then: true, else: false } } } }

and it didn't work. I also tried passing a lambda expression but it won't build either. Any idea if this is possible or do I need to use two seperate updateOne statements to the the current IsDefault to false, and the new one to true?

you can achieve it with an aggregation pipeline update like this:

db.collection.updateMany(
    {},
    [
        {
            $set: {
                IsDefault: {
                    $eq: ["$_id", ObjectId("5f65c2fcaf29d00898173d03")]
                }
            }
        }
    ])

here's a full example using mongodb.entities:

 using MongoDB.Entities; using System.Threading.Tasks; namespace StackOverflow { public class Book : Entity { public string Title { get; set; } public bool IsDefault { get; set; } } static class Program { private static async Task Main() { await DB.InitAsync("test", "localhost"); var books = new[] { new Book { Title = "book 1"}, new Book { Title = "book 2"}, new Book { Title = "book 3"} }; await books.SaveAsync(); var stage = new Template<Book>(@" { $set: { IsDefault: { $eq: ['$_id', ObjectId('<idvalue>')] } } }") .Tag("idvalue", books[1].ID); await DB.Update<Book>() .Match(_ => true) .WithPipelineStage(stage) .ExecutePipelineAsync(); } } }

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