简体   繁体   English

C# Mongo 驱动程序:使用连接和 UpdateManyAsync 更新查询

[英]C# Mongo driver: Update query using joins and UpdateManyAsync

I have 2 collections我有 2 个集合

ProductCategory产品分类

_id name active _id 名称有效

Product产品

_id CategoryId DateUpdated _id CategoryId DateUpdated

I can do the update in one collection by creating a filter and using UpdateManyAsync, like this:我可以通过创建过滤器并使用 UpdateManyAsync 在一个集合中进行更新,如下所示:

var update = Builders<ProductCategory>.Update
                .Set(x => x.Active ,false);


var filter = Builders<ProductCategory>.Filter.Where(
                x => x.Active == true);

var result = await Collection.UpdateManyAsync(filter, update);

Now I want to update Active field on ProductCategory if any documents with DateUpdated more than 1 day compared to current date现在我想更新 ProductCategory 上的 Active 字段,如果任何文档的 DateUpdated 与当前日期相比超过 1 天

it may the same as sql query:它可能与 sql 查询相同:

UPDATE A
SET active = false
FROM ProductCategory A
JOIN Product B
    ON A._id= B.CategoryId
WHERE DATEDIFF(Getdate(), B.DateCreated) >= 1

afaik you cannot update entities based on the result of a lookup/join in mongodb via a single command. afaik 您无法通过单个命令根据在 mongodb 中查找/加入的结果更新实体。 instead you'd have to first retrieve the IDs of categories and then do the update operation like below:相反,您必须首先检索类别的 ID,然后执行如下更新操作:

var inactiveCatIDs = collection.AsQueryable()
                               .Where(p => p.DateUpdated <= DateTime.UtcNow.AddDays(-1))
                               .Select(p => p.CategoryID)
                               .ToArray();

collection.UpdateMany(c => inactiveCatIDs.Contains(c.ID),
                      Builders<ProductCategory>.Update.Set(c => c.Active, false));

here's a test program:这是一个测试程序:

 using MongoDB.Entities; using MongoDB.Entities.Core; using System; using System.Linq; namespace StackOverflow { public class Product : Entity { public DateTime DateUpdated { get; set; } public string CategoryID { get; set; } } public class ProductCategory : Entity { public bool Active { get; set; } } public class Program { private static void Main(string[] args) { new DB("test", "localhost"); var cat1 = new ProductCategory { Active = true }; cat1.Save(); var cat2 = new ProductCategory { Active = true }; cat2.Save(); (new[] { new Product { CategoryID = cat1.ID, DateUpdated = DateTime.UtcNow.AddDays(-1.5) }, new Product { CategoryID = cat2.ID, DateUpdated = DateTime.UtcNow }}).Save(); ; var inactiveCatIDs = DB.Queryable<Product>() .Where(p => p.DateUpdated <= DateTime.UtcNow.AddDays(-1)) .Select(p => p.CategoryID) .ToArray(); DB.Update<ProductCategory>() .Match(c => inactiveCatIDs.Contains(c.ID)) .Modify(c => c.Active, false) .Execute(); } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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