我在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();
}
}
答案 0 :(得分:5)
您可以使用FindAll返回的游标上的SetFields在C#中执行此操作:
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;
答案 1 :(得分:0)
db.users.find({_id: user_id},
{'address.country': 1});
这将为您提供类似
的文档{"_id": ObjectId('4efb78234ee9184d8b5a4e92'),
"address": {"country": "Russia"}}