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

问题描述 投票:1回答:1

[嗨,我是mongoDB和C#的新手。我想从我的收藏中找到特定文件的最小值。

我创建了以下课程

     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}.'

[我尝试使用FindAs()找到here的另一种方法。

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

再次,我也很幸运。

有人可以向我解释如何从我的收藏中正确获取最小值。谢谢您的时间。

c# mongodb mongodb-query mongodb-.net-driver
1个回答
0
投票

您从MongoDB的查询/聚合返回的内容必须是一个对象,如果要从整个集合中获取最小值/最大值,则需要以恒定值$group该集合:

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

var result = q.First().MinVal;
© www.soinside.com 2019 - 2024. All rights reserved.