Project matched array element to new property

I have a sample document like

{
    "_id": 1111,
    "propertyToProjectTo": null,
    "arrayOfObjects": [
    {
        "key": 1,
        "values": {
           "value1": "val1",
           "value2": "val2"
        }
    },
    {
        "key": 2,
        "values": {
           "value1": "val3",
           "value2": "val4"
        }
    }
  ]
}

arrayOfObjects contains distinct values for key, so it is not possible to have identical key value in arrayOfObjects.

I need a projection that would ignore arrayOfObjects in projection, but insted, it would project value1 for given key to propertyToProjectTo.

Example:
Given document after projection (key=1) would look like:

{
    "_id": 1111,
    "propertyToProjectTo": "val1"
}

Hi @Marko_Saravanja,
Try this:

db.myCollection.aggregate([{$match: {
  "arrayOfObjects.key": 1
}}, {$unwind: {
  path: "$arrayOfObjects",
}}, {$match: {
  "arrayOfObjects.key": 1
}}, {$project: {
  propertyToProjectTo: "$arrayOfObjects.values.value1"
}}])

Thanks,
Rafael,

Hi @Rafael_Green. Thank you for your response, it is the light at the end of my tunnel :slight_smile:

I would like to know how to include that in my projection:

var results = await Collection.Find(matchFilter).Project<ResponseObject>(projection_goes_here)

what library you are using?

<PackageReference Include="MongoDB.Driver" Version="2.12.4" />

I’m not familiar with C# but give this a try:

var pipeline = new BsonArray {
    new BsonDocument("$match", 
    new BsonDocument("arrayOfObjects.key", 1)),
    new BsonDocument("$unwind", 
    new BsonDocument("path", "$arrayOfObjects")),
    new BsonDocument("$match", 
    new BsonDocument("arrayOfObjects.key", 1)),
    new BsonDocument("$project", 
    new BsonDocument("propertyToProjectTo", "$arrayOfObjects.values.value1"))
}

var result = await Collection.Aggregate(pipeline)

1 Like

@Rafael_Green it works like this, but before marking your answer as Solution, I would like to wait if someone offers strong typed Solution. I try to avoid this kind of queries because of possible typos.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.