如何使用 C# 驱动程序 2.10.4 查找 MongoDB 中特定字段的最小值

How to find the min value of a specific field in MongoDB using C# driver 2.10.4

大家好,我是 mongoDB 和 C# 的新手。我想从我的 collection.

中找到特定文件的最小值

我创建了以下 class

     public class GlobalUrbanPoint
        {
            [BsonId]
            public ObjectId  Id{ get; set; }
            public double LATITUDE { get; set; }
            public double LONGITUDE { get; set; }
            ...
        }

对于连接和其他操作,我有以下功能。

     public class MongoCRUD
        {
            private IMongoDatabase db;

            public MongoCRUD(string database)
            {
                var client = new MongoClient();
                db = client.GetDatabase(database);
            }
            ...
            public void NormalizeCoordinates<T>(string table)
            {
                var collection = db.GetCollection<T>(table);
                // something is wrong the selection  
                var result = collection.AsQueryable<T>().Select(LATITUDE => LATITUDE).Min<T>();
                Console.WriteLine(result);
            }
        }

这是Main函数:

    using System;
    using System.Collections.Generic;
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;

    static void Main(string[] args)
        {
            MongoCRUD db = new MongoCRUD("testClass");

            var newTable = "points";

            /* find The min value*/
            db.NormalizeCoordinates<GlobalUrbanPoint>(newTable);
         }

如果我 运行 我得到一个异常:System.NotSupportedException: '$project or $group does not support {document}.'

我尝试了一种不同的方法,我发现 here 使用 FindAs()。

    var cursor =  collection.FindAs<T>(Query.And()).SetSortOrder(SortBy.Ascending(fieldName)).SetLimit(1).SetFields(fieldName);

再一次,我有同样的运气。

谁能解释一下如何从我的 collection 中正确获取最小值。 谢谢您的宝贵时间。

您从 MongoDB 的 query/aggregation 返回的内容必须是一个对象,如果您想从整个集合中获取 min/max 值,您需要 $group 该集合按常量值:

var q = collection.Aggregate()
                  .Group(
                      x => 1,
                      gr => new {MinVal = gr.Min(f => f.LONGITUDE)});

var result = q.First().MinVal;