MongoDB& Web API - 无法理解如何使用过滤器

时间:2016-03-22 08:48:36

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

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

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

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

    我在网上尝试了很多例子。对于早期版本的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;
            }
        }
    

1 个答案:

答案 0 :(得分:4)

您正在使用旧版驱动程序方法,以下是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/