简体   繁体   中英

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

Hi i am new in mongoDB and in C#. I want to find the min value of a specific filed from my collection.

I have created the following class

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

For the operation I have following function for the connection and other.

     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);
            }
        }

This is the 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);
         }

If I run this I get an exception: System.NotSupportedException: '$project or $group does not support {document}.'

I have try and a different approach that i found here with the use of FindAs().

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

Again, I have the same luck.

Can someone explain me how to get the min value properly from my collection. Thank you, for your time.

What you're returning from MongoDB's query/aggregation needs to be an object and if you want to get min/max values from entire collection you need to $group that collection by a constant value:

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

var result = q.First().MinVal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM