【问题标题】:Query nested objects from MongoDB从 MongoDB 查询嵌套对象
【发布时间】:2011-12-29 06:50:25
【问题描述】:

我在 SSIS 中创建了一个脚本来从 MongoDB 检索数据。虽然查询常规文档没有任何问题,但我不确定如何从嵌套文档中检索值。例如,扩展的“地址”包含“国家”、“州”、“城市”、“街道”和“邮编”。我只对检索“国家”(字段)值感兴趣。从理论上讲,我理解它应该类似于“Address.Country”,但我不知道如何在我的代码中实现它。实现这一目标的最佳方法是什么?

这是检索所有其他文档的代码:

    public override void CreateNewOutputRows()
    {
        string connectionString = "mongodb://localhost";
        MongoServer myMongo = MongoServer.Create(connectionString);
        myMongo.Connect();
        var db = myMongo.GetDatabase("UserDB");
        /*ICursor<BsonDocument> cursor = db.GetCollection<BsonDocument>("UserDB").FindAll();*/
        foreach (BsonDocument document in db.GetCollection<BsonDocument>("UserDB").FindAll())
        {
            this.UserDBBuffer.AddRow();
            this.UserDBBuffer.ID = document["_id"] == null ? "" : document["_id"].ToString();

            this.UserDBBuffer.PrimaryEmail = document["primary_email"] == null ? "" : document["primary_email"].ToString();
            this.UserDBBuffer.Gender = document["gender"] == null ? "" : document["gender"].ToString();

        }
}

【问题讨论】:

    标签: c# mongodb ssis nested bson


    【解决方案1】:

    您可以在 C# 中使用 FindAll 返回的光标上的 SetFields 来做到这一点:

    var fields = Fields.Include("Address.Country");
    foreach (var document in collection.FindAll().SetFields(fields))
    {
        Console.WriteLine(document.ToJson());
    }
    

    您可以使用以下方法从返回的文档中提取 Country 值:

    var country = document["Address"].AsBsonDocument["Country"].AsString;
    

    【讨论】:

    • 谢谢!这正是我所需要的!
    • 现在,下一个挑战是如何从数组中提取数据。例如,其中一个数组如下所示:“devices -> Document -> device_data -> model”或“devices -> Document -> device_data -> brand”。如何提取设备的型号或品牌?再次感谢您的帮助!
    • 我将“地址”更改为“位置”(另一个包含国家/地区的字段),我的脚本返回“未找到国家”,我不知道为什么...
    【解决方案2】:
    db.users.find({_id: user_id},
                  {'address.country': 1});
    

    这会给你一个像

    这样的文件
    {"_id": ObjectId('4efb78234ee9184d8b5a4e92'), 
     "address": {"country": "Russia"}}
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 2012-07-23
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多