4

I created a script in SSIS to retrieve data from MongoDB. While I don't have any issues querying regular documents, I am not sure how to retrieve values from nested documents. For example, "Address" expanded contains "Country", "State", "City", "Street", and "Zip". I am interested in retrieving the "Country" (field) values only. In theory, I understand that it 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 that?

This is the code that retrieves all the 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();

        }
}

2 Answers 2

5

You can do that 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;
Sign up to request clarification or add additional context in comments.

2 Comments

Now, the next challenge is how to extract data from an array. For example, one of the arrays looks like this: "devices -> Document -> device_data -> model" or "devices -> Document -> device_data -> brand". How do I extract the model or the brand of the device? Again, thanks a lot for your help!
I changed "Address" to "location" (another field containing country) and my scripts returns "country not found" and I can't figure out why...
0
db.users.find({_id: user_id},
              {'address.country': 1});

This will get you a document like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.