如何使用C#mongodriver客户端运行bson命令访问嵌套项目结构?

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

如何通过编写ansi mongo脚本访问嵌套的mongodb结构来运行简单的mongodb命令?但是它不起作用,因为它是不正确的。我正在通过谷歌搜索寻找答案,但是找不到最佳答案。我知道在C#中使用mongodb就像是一种折磨。请给我很大的建议。因为我精疲力竭地在互联网上进行研究。我的代码是位姿势代码。这是我的一种愿望。另外,请看一下我的图片以了解我的mongodb json结构的结构。

  var customerinfos = db_ScaleGrid.RunCommand<BsonDocument>(new BsonDocument("db.getCollection('customers').find({'Items.0.Source.CustomerInfo':{$exists:true}})",""));
            foreach (var customerinfo in customerinfos)
            {
                var customerid = customerinfo["customerid"];
                var customerName = customerinfo["customerName"];
            }

enter image description here

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

我希望我已经正确理解了您的结构和要求。如果没有,请告诉我,我将相应地答复。您可以使用mongodb c#驱动程序的AsQueryable界面轻松访问客户信息,如下所示:

var collection = new MongoClient("mongodb://localhost")
                    .GetDatabase("test")
                    .GetCollection<Customer>("customers");

var result = collection.AsQueryable()
                .Select(c => c.Items[0].Source.CustomerInfo)
                .ToArray();

这是一个强类型的测试程序:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
using System.Linq;

namespace StackOverFlow
{
    public class Customer : Entity
    {
        public Item[] Items { get; set; }
    }

    public class Item
    {
        public Source Source { get; set; }
    }

    public class Source
    {
        public CustomerInfo CustomerInfo { get; set; }
    }

    public class CustomerInfo
    {
        public string CustomerID { get; set; }
        public string CustomerName { get; set; }
    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            var customer = new Customer
            {
                Items = new[]
                {
                    new Item
                    {
                        Source = new Source {
                            CustomerInfo = new CustomerInfo
                            {
                                CustomerID = "xxxxxxx",
                                CustomerName = "customer one"
                            }
                        }
                    }
                }
            };

            customer.Save();

            var result = DB.Queryable<Customer>()
                           .Select(c => c.Items[0].Source.CustomerInfo)
                           .ToArray();

            foreach (var info in result)
            {
                Console.WriteLine($"id: {info.CustomerName} / name: {info.CustomerName}");
            }

            Console.ReadKey();
        }
    }
}

以上测试程序将我的库MongoDB.Entities简化了。如果您对官方司机的冗长不知所措,则不妨查看我的图书馆。

© www.soinside.com 2019 - 2024. All rights reserved.