【问题标题】:How to query MongoDb for id field and make a list of id's in c#如何在 C# 中查询 MongoDb 的 id 字段并制作 id 列表
【发布时间】:2019-11-20 20:06:42
【问题描述】:

我正在尝试遍历 MongoDb 数据库集合中的 id。目标是遍历这些 id 并使用 id 创建具有不同 id 的 json 文件。我相信我写的查询返回了所有的 id,但是我得到了下面的错误。

Inner Exception 1:
FormatException: '9a1c458c-82Dd-43b4-a963-76a96d374580' is not a valid 24 digit hex string.

以下是我获取所有 id 的查询

var thingsDoc = demoThings.AsQueryable().Where(a => a._id != null).ToList();

下面是我的事物属性类

public class Things
    {
        [BsonRepresentation(BsonType.ObjectId)]
        public ObjectId _id { get; set; }
    }

我认为问题在于如何定义属性。还是我的查询有问题?从研究中我知道它抱怨的原因是因为格式中的破折号。但没有找到任何解决方法来解决这个问题。非常感谢您的帮助。

【问题讨论】:

    标签: c# mongodb bson objectid formatexception


    【解决方案1】:

    我已经能够解决我的问题。似乎使用模型并在 ObjectId 和 String 之间进行转换使我的程序无法运行。所以下面的方法解决了这个问题。

    var demoThings = DBConnect.CosmosClient.GetCollection<BsonDocument>("Things");
                foreach(var doc in demoThings.Find(x => x["_id"] != "").ToList())
                {
                    thingList.Add(doc["_id"].ToString());
                }
    

    我的目标是获取集合并添加所有 _id 并将它们添加到列表中,以便我可以模拟 json 文件中的数据并将 id 附加到 JSON。通过上面的操作,我能够将 id 和它们抓取到一个列表中。

    【讨论】:

      【解决方案2】:

      将 [BsonRepresentation (BsonType.ObjectId)] 更改为 [BsonId] 很可能会解决您的问题。

      How can I tell the MongoDB C# driver to store all Guids in string format?

      Difference between decorating a property in C# with BsonRepresentation(BsonType.ObjectId) vs BsonId vs ObjectId

      编辑:

      我创建了一个简单的工作示例。 这是一个模型。

      public class Model
      {
          [BsonId]
          [BsonElement("id")]
          [BsonRepresentation(BsonType.ObjectId)]
          public ObjectId ID { get; set; }
      
          public Model(ObjectId id)
          {
              ID = id;
          }
      }
      

      这是一个简单的服务类:

      public interface IModelService
      {
          Task<IEnumerable<string>> GetModelsIds();
          Task AddModel();
      }
      
      public class ModelService : IModelService
      {
          private const string CollectionName = "Models";
      
          private readonly MongoClient client;
          private readonly IMongoDatabase _mongoDatabase;
          private readonly IMongoCollection<Model> _modelsCollection;
      
          public ModelService()
          {
              client = new MongoClient("mongodb://localhost:27017");
              _mongoDatabase = client.GetDatabase("MongoStackOverFlow");
              _productsCollection = _mongoDatabase.GetCollection<Model>(CollectionName);
          }
      
          public async Task<IEnumerable<string>> GetModelsIds()
          {
              var models =  await _productsCollection.Find(p => p.ID != null).ToListAsync();
              return models.Select(x => x.ID.ToString());
          }
      
          public async Task AddModel()
          {
              var model = new Model(new ObjectId());
      
              await _productsCollection.InsertOneAsync(model);
          }
      }
      

      以及入口点:

      class Program
      {
          static async Task Main(string[] args)
          {
              IModelService modelService = new ModelService();
              var modelsIds = await modelService.GetModelsIds();
      
              if (!modelsIds.Any())
              {
                  for (int i = 0; i <= 10; i++)
                  {
                      await modelService.AddModel();
                  }
              }
      
              Task.WaitAll();
      
              foreach (var modelId in modelsIds)
              {
                  Console.WriteLine($"ProductID: {modelId}");
              }
          }
      }
      

      【讨论】:

      • 我的 _id 属性应该是字符串还是对象 ID?
      • 好的,我有另一个想法,将您的对象 id 更改为字符串,并将属性名称更改为 Id、ID 或 _id 以外的其他内容。
      • 我要保留 [BsonId] 吗?
      • 现在我得到这个错误,'元素'x'与 SimRunnerTest.Things 类的任何字段或属性都不匹配。'
      • 我尝试添加这个,[BsonRepresentation(BsonType.ObjectId)],我没有收到任何错误。我有一段代码将所有 id 添加到列表中。但我的清单是空的
      猜你喜欢
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 2013-08-15
      • 1970-01-01
      • 2011-12-06
      • 2021-06-14
      相关资源
      最近更新 更多