Request nested objects from MongoDB

In SSIS, I created a script to retrieve data from MongoDB. Although I don't have any problems with querying regular documents, I'm not sure how to extract values ​​from nested documents. For example, an extended “Address” contains “Country,” “State,” “City,” “Street,” and “Postal Code.” I’m interested in getting only the "Country" (field) values. Theoretically, I understand that this should be something like "Address.Country", but I do not know how to implement it in my code. What is the best way to achieve this?

This is the code that retrieves all other documents:

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(); } } 
+4
source share
2 answers

You can do this in C # using SetFields on the cursor returned by FindAll:

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

You can extract the Country value from the returned document using:

 var country = document["Address"].AsBsonDocument["Country"].AsString; 
+5
source
 db.users.find({_id: user_id}, {'address.country': 1}); 

This will give you a document like

 {"_id": ObjectId('4efb78234ee9184d8b5a4e92'), "address": {"country": "Russia"}} 
0
source

Source: https://habr.com/ru/post/1388364/


All Articles