[CSHARP-609] Add support for $elemMatch projection to Fields builder Created: 22/Oct/12  Updated: 20/Mar/14  Resolved: 11/Mar/13

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.6
Fix Version/s: 1.8

Type: Improvement Priority: Major - P3
Reporter: Robert Stam Assignee: Craig Wilson
Resolution: Done Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
is duplicated by CSHARP-683 Add new features to Query builder for... Closed

 Description   

Server 2.2 added support for $elemMatch projection for array fields. See:

http://docs.mongodb.org/manual/reference/projection/elemMatch/F

Add support for this type of projection to the Fields builders (untyped and typed).



 Comments   
Comment by Robert Stam [ 22/Oct/12 ]

Here's a workaround you can use until this ticket is implemented:

var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase("test");
var collection = database.GetCollection("test");
 
var id = ObjectId.GenerateNewId();
var document = new BsonDocument
{
    { "_id", id },
    { "zipcode", 63109 },
    { "dependents", new BsonArray {
        new BsonDocument { { "name", "john" }, { "school", 102 }, { "age", 10 } },
        new BsonDocument { { "name", "jess" }, { "school", 102 }, { "age", 11 } },
        new BsonDocument { { "name", "jeff" }, { "school", 108 }, { "age", 15 } }
    }}
};
if (collection.Exists()) { collection.Drop(); }
collection.Insert(document);
 
var query = Query.EQ("zipcode", 63109);
var fields = new FieldsDocument
{
    { "_id", 0 },
    { "dependents", new BsonDocument("$elemMatch", new BsonDocument("school", 102)) }
};
foreach (var partialDocument in collection.Find(query).SetFields(fields))
{
    Console.WriteLine(partialDocument.ToJson());
}

Generated at Wed Feb 07 21:37:19 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.