cayako95436
cayako95436

Reputation: 1

c# and mongodb include or exclude element of array using projection

Given the document in my cloud mongoDB

{
 
 _id: ObjectId("5effaa5662679b5af2c58829"),
 email: “[email protected]”,
 name: {given: “Jesse”, family: “Xiao”},
 age: 31,
 addresses: [
              {
               label: “home”,
               street: “101 Elm Street”,
               city: “Springfield”,
               state: “CA”,
               zip: “90000”,
               country: “US”
              },
             { 
               label: “mom”,
               street: “555 Main Street”,
               city: “Jonestown”,
               province: “Ontario”,
               country: “CA”
              }
            ]
              
}

im creating a program using c# where i want to display all the elements in the collection. im new and following the documentation (https://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/definitions/) i cant figure how to only display the email element and the addresses showing only [label][city][country].

when i try this, i get all the information in addresses.

var projection = Builders<BsonDocument>.Projection.Include("email").Include("addresses").Exclude("_id");

how can i retrieve the addresses' label, city and country and exclude the rest?

Thanks a lot!

Upvotes: 0

Views: 743

Answers (1)

Yong Shun
Yong Shun

Reputation: 51450

Specify the nested fields in the array to be included with dot notation.

var projection = Builders<BsonDocument>.Projection
                .Include("email")
                .Include("addresses.label")
                .Include("addresses.city")
                .Include("addresses.country")
                .Exclude("_id");

Output

enter image description here

Upvotes: 0

Related Questions