簡體   English   中英

如何使用 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# 的新手。 我想從我的收藏中找到特定文件的最小值。

我創建了以下 class

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

對於操作,我有以下 function 用於連接和其他。

     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的 function:

    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() 的不同方法。

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

再次,我有同樣的運氣。

有人可以解釋一下如何從我的收藏中正確獲取最小值。 感謝您的時間。

您從 MongoDB 的查詢/聚合返回的內容必須是 object,如果您想從整個集合中獲取最小/最大值,您需要按一個常量值對該集合進行$group

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

var result = q.First().MinVal;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM