【问题标题】:MongoDB & Web API - can't understand how to use filtersMongoDB & Web API - 无法理解如何使用过滤器
【发布时间】:2016-03-22 08:48:35
【问题描述】:

我正在尝试使用 C# Web API 在 MongoDB 上执行基本的 CRUD。在线的所有示例都是针对已弃用的方法,我根本无法使新方法起作用。

下面代码中我需要帮助的地方:

  1. 删除集合中的所有项目 - 删除所有项目的语法。
  2. 获取集合中的所有项目 - 过滤以获取所有内容
  3. 按 id 获取 = 按 id 选择的语法

我在网上试过很多例子。大多数已被以前版本的 MongoDB 弃用,官方的 Mongo 文档也没有帮助,我怀疑我的代码涉及 WebAPI 类,示例不适合。

感谢您的帮助!

这是类:

  public class template
{

    [BsonId]
    public string templateUniqueId { get; set; }

    public string outsideClientId { get; set; }

    public string ClientId { get; set; }

    public string templateFieldsData { get; set; }

    public bool isActive { get; set; }

}

还有我的存储库实现(if 的一部分):

public class templateRepository : ItemplateRepository
    {
        public MongoClient client;
        public IMongoDatabase database;
        public IMongoCollection<template> templatesCollection;
        public templateRepository()
        {
            string connectionString = ConfigurationManager.AppSettings["mongoconnection"];
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                connectionString = "mongodb://localhost:27017";
            }

            client = new MongoClient(connectionString);
            database = client.GetDatabase(ConfigurationManager.AppSettings["mongo_personal"]);

            templatesCollection = database.GetCollection<template>("templates");
            //var persons = await collection.Find(new BsonDocument()).ToListAsync();


            // Reset database and add some default entries
            FilterDefinition<template> f;

            var result = templatesCollection.DeleteMany(f); // this line should remove all items

            for (int index = 1; index < 5; index++)
            {
                template template1 = new template
                {
                    templateUniqueId = string.Format("t{0}", index.ToString()),
                    outsideClientId= string.Format("t{0}", index.ToString()),
                    ClientId = string.Format("t{0}", index.ToString()),
                    isActive = true,
                    templateFieldsData = "sharon"

                };
                AddTemplate(template1);
            }
        }

        public void AddTemplate(template templateIn)
        {
            database.GetCollection<template>("templates").InsertOne(templateIn);
        }

        public IEnumerable<template> GetAllTemplates()
        {
            var templates = database.GetCollection<template>("templates").Find({ }); // get all templates
            return templates;
        }


        public template GetTemplate(string id)
        {
            IMongoQuery query = Query.EQ("_id", id);
            return templatesCollection.Find(query).FirstOrDefault();
        }

        public bool UpdateTemplate(string id, template item)
        {
            IMongoQuery query = Query.EQ("_id", id);
            item.LastModified = DateTime.UtcNow;
            IMongoUpdate update = Update
                .Set("outsideClientId", item.outsideClientId)
               .Set("ClientId", item.ClientId)
                .Set("isActive", item.isActive)
               .Set("templateFieldsData", item.templateFieldsData);
            SafeModeResult result = templatesCollection.Update(query, update);
            return result.UpdatedExisting;
        }
    }

【问题讨论】:

    标签: c# mongodb asp.net-web-api


    【解决方案1】:

    您使用的是旧版驱动程序方法,以下是MongoDB C# Driver 2.2 的一些示例:

    删除集合中的所有项目,删除所有的语法。

    coll.DeleteMany(FilterDefinition<template>.Empty);
    

    获取集合中的所有项目,过滤获取全部

    var results = coll.Find(FilterDefinition<template>.Empty).ToList();
    

    按 id 获取,按 id 选择的语法

    var filter = Builders<template>.Filter.Eq(t=>t.templateUniqueId, id);
    var result = coll.Find(filter).FirstOrDefault();
    

    此外,对于您的 更新方法,您可以使用以下语法:

    var filter = Builders<template>.Filter.Eq(t=>t.templateUniqueId, id);
    var update = Builders<template>.Update
        .Set(t=>t.outsideClientId, item.outsideClientId)
        .Set(t=>t.ClientId, item.ClientId)
        .Set(t=>t.isActive, item.isActive)
        .Set(t=>t.templateFieldsData, item.templateFieldsData);
    
    var updateResult = coll.UpdateOne(filter, update);
    return result.ModifiedCount > 0;
    

    有关定义和构建器的更多信息: http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/definitions/

    【讨论】:

    • 谢谢!只是一个小小的评论,我使用“UpdateOne”作为更新不可用的更新语法。 - 谢谢!!!!!!
    • 感谢您的警告,相应地更新了答案:)
    猜你喜欢
    • 1970-01-01
    • 2013-08-22
    • 2019-10-30
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    相关资源
    最近更新 更多