MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

How to get object from array from mongodb using C#

I have the following JSON in MongoDB:

    "ScurvePlanName": "PipeTrack",
    "ScurvePlanData": [{
        "Levels": "Mechanical",
        "Scope": null,
        "StartDate": null,
        "EndDate": null,
        "Weightage": {
            "$numberDouble": "20"
        },
        "ParentLevels": "",
        "ActivityId": null,
        "IsInternal": false
    }, {
        "Levels": "Welding",
        "Scope": {
            "$numberDouble": "2000"
        },
        "StartDate": "898989667687687768768",
        "EndDate": "898989667687687768768",
        "Weightage": {
            "$numberDouble": "5"
        },
        "ParentLevels": "Mechanical",
        "ActivityId": {
            "$numberDouble": "5"
        },
        "IsInternal": true
    }]
}

I only need objects inside the array which is the value of key “ScurvePlanData”.

This is my current code:

var fdbFiller= Builders<BsonDocument>.Filter.Eq("ScurvePlanName", SCurveName);
 var projection = Builders<BsonDocument>.Projection.Include("ScurvePlanData");
            var cursor = collection.Find<BsonDocument>
(fdbFiller).Project(projection).ToCursor();

that means in need only the array which is side the key “SCurvePlanData”

Hi @Rajesh_Yadav, welcome to the forum!

I only need objects inside the array which is the value of key “ScurvePlanData”.

It’s not entire clear from the question, but I assumed that what you’re wanting to return is :

{ "Levels": "Mechanical",  Scope: null, ...}
{ "Levels": "Welding", Scope: {"$numberDouble": "2000"}, ...}

Instead of the current result with your snippet example of :

{ "ScurvePlanData" : [
    { "Levels" : "Mechanical", "Scope" : null, ... }, 
    { "Levels" : "Welding", "Scope" : { "$numberDouble" : "2000" }, .... }] 
}

If this is the case, you can use MongoDB Aggregation Pipeline to manipulate the document(s). For example:

var pipeline = new BsonDocument[]{
    new BsonDocument{ 
        {"$match", new BsonDocument{
            {"ScurvePlanName", "PipeTrack"}
        }}}, 
        new BsonDocument{ 
            {"$unwind", "$ScurvePlanData"}
        },
        new BsonDocument{
            {"$replaceRoot", new BsonDocument{
                 {"newRoot", "$ScurvePlanData"}
        }}}
};
var docs = collection.Aggregate<BsonDocument>(pipeline).ToList();

If you have class mapping for the collection, see also the PipelineStageDefinitionBuilder:

I’d also recommend to review MongoDB Aggregation Quick Reference to learn more.

If this is not what you’re after, please clarify with a desired document output example and also version of MongoDB .NET driver that you’re using.

Regards,
Wan.