【问题标题】:Query MongoDB in C# using LINQ使用 LINQ 在 C# 中查询 MongoDB
【发布时间】:2019-04-24 20:44:10
【问题描述】:

我有一个简单的类来表示 MongoDB 文档中的字段

class Measurement
{
    public ObjectId id { get; set; }
    public int s { get; set; }
    public int[] p { get; set; }
    public int dt { get; set; }
    public int ml { get; set; }
}

我正在尝试使用

获取符合我的条件的文档
var collection = database.GetCollection<Measurement>(mongoCollectionName);
    var query = from a in collection.AsQueryable<Measurement>()
                where a.dt > 100
                select a;

当条件被删除时,我确实收到了所有文件,但没有条件。响应说没有匹配的文件,但有(例如 dt=1538555)

查询看起来像这样 {aggregate([{ "$match" : { "dt" : { "$gt" : 100 } } }])}。 我使用来自这个线程和 mongodb 文档的响应来构建我的示例 MongoDB C# Aggregation with LINQ

如果能解决我可能犯的愚蠢错误,我将不胜感激

【问题讨论】:

    标签: c# mongodb linq


    【解决方案1】:

    我不再直接使用 c# 驱动程序,所以我的解决方案是使用 MongoDAL。

    using System;
    using System.Linq;
    using MongoDAL;
    
    namespace Example
    {
        class Measurement : Entity
        {
            public int s { get; set; }
            public int[] p { get; set; }
            public int dt { get; set; }
            public int ml { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                new DB("measurements");
    
                var measurement1 = new Measurement
                {
                    s = 10,
                    ml = 20,
                    dt = 100,
                    p = new int[] { 1, 2, 3, 4, 5 }
                };
    
                var measurement2 = new Measurement
                {
                    s = 11,
                    ml = 22,
                    dt = 200,
                    p = new int[] { 1, 2, 3, 4, 5 }
                };
    
                measurement1.Save();
                measurement2.Save();
    
                var result = (from m in DB.Collection<Measurement>()
                              where m.dt > 100
                              select m).ToArray();
    
                Console.ReadKey();
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多