我如何只选择一个数据并显示?

时间:2017-01-17 10:12:55

标签: c# mongodb mongodb-.net-driver

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Driver.Builders;

namespace ConsoleApplication1
{
    class container
    {
        public string _Id { get; set; }
        public string Node { get; set; }
        public int SignalSTR { get; set; }
        public float Battery { get; set; }
        public float CEL { get; set; }
        public float WT { get; set; }
        public string OnlineSTAT { get; set; }
        public string FirmVER { get; set; }
        public Int64 Timestamp { get; set; }

    }

    class Program
    {
        static void Main(string[] args)

        {
            CallMain(args).Wait();
            Console.ReadLine();
        }
        static async Task CallMain(string[] args)
        {
            var connectionString = "mongodb://localhost:27017";
            var client = new MongoClient(connectionString);
            //var server = client.GetServer();
            var database = client.GetDatabase("test");
            //var collection = database.GetCollection<Entity>("entities");
            var collection = database.GetCollection<BsonDocument>("container");
            var builder = Builders<BsonDocument>.Filter;
            var filt = builder.Eq("Node", "001_Iron_Nail") & builder.Eq("WT", "4.3");



            /* Method 1
            using (var cursor = await collection.Find(new BsonDocument()).ToCursorAsync())
            {
                while (await cursor.MoveNextAsync())
                {
                    foreach (var doc in cursor.Current)
                    {
                        Console.WriteLine(doc);
                    }
                }
            } */

            // Method 2
            //var list = await collection.Find(filt).ToListAsync();

            var list = await collection.Find(filt).ToListAsync();
            foreach (var dox in list)
            {
                Console.WriteLine(dox);
            }

            // Method 3
            // await collection.Find(new BsonDocument()).ForEachAsync(X => Console.WriteLine(X));

        } 
    }
}

上面的代码我可以过滤一些条件来显示我的'test'数据库中名为'container'的集合中的所有数据。想问一下我该如何打印出一些选定的valiue。像例子。我只想要电池:

Battery 3.5
Battery 3.6
Battery 3.7           

3 个答案:

答案 0 :(得分:0)

var list = await collection.Find(filt).ToListAsync();
for (int ii=0; ii<list.Count; ii++)
{
    Console.WriteLine("Battery " + list[ii].Battery);
}

答案 1 :(得分:0)

你可以像这样输出:

Console.WriteLine(string.Format("{0} {1}", dox["Node"].ToString(), dox["WT"].ToString());

答案 2 :(得分:0)

您将获得仅包含电池的清单:

collection.Find(filt).Project(x => new {x.Battery}).ToList();

备选方案,你可以从mongo获取所有数据并在客户端上过滤它:

collection.Find(filt).ToEnumerable().Select(x => x.Battery);