mongodbmongo-c-driver

MongoDB project nested element in _id field


I'm stuck in something very stupid but I can't get out from my own.

MongoDB v4.2 and I have a collection with documents like this:

{"_id":{"A":"***","B":0}}, "some other fields"...

I'm working on top of mongo-c driver and I want to query only the "_id.B" field but I don't know how I can do it. I have tried:

  1. "projection":{"_id.B":1}: It returns me the whole _id object. _id.A & _id.B.
  2. "projection":{"_id.A":0,"All other fields except _id.B":0}: Returns same as above.
  3. "projection":{"_id.A":0,"_id.B":1}: Returns nothing.

How I can do it to get only some object elements when this object is inside the _id field? The first option works for me with objects that aren't inside the _id field but not here.

Best regards, thanks for your time.

Héctor


Solution

  • You can use MongoDB's $project in aggregation to do this. You can also use $addFields to get _id.B into new field + all other fields in document & finally project _id :0.

    Code:

    var coll = localDb.GetCollection("yourCollectionName"); 
    
    var project = new BsonDocument 
    { 
        { 
            "$project", 
            new BsonDocument 
                { 
                    { "_id.B": 1 }
                } 
        } 
    }
    var pipeline = new[] { project };
    var result = coll.Aggregate(pipeline);
    

    Test : MongoDB-Playground