在mongo中为C#排除数组元素

时间:2016-10-26 20:03:22

标签: c# mongodb

使用以下json

{
    "_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
    "name" : "MongoDB",
    "notes" : [
                {
                  "title" : "Hello MongoDB",
                  "content" : "Hello MongoDB"
                },
                {
                  "title" : "ReplicaSet MongoDB",
                  "content" : "ReplicaSet MongoDB"
                }
             ]
    }

我想使用C#projecttion来排除它的标题不是“Hello MongoDB”的数组元素

1 个答案:

答案 0 :(得分:0)

是的,可以使用聚合框架,如果您对此没有问题,请使用以下MONGO查询

db.ToTest.aggregate([
    { $unwind : "$notes" },
    { "$match" : { "notes.title" : { "$ne" : "Hello MongoDB" } } },
    { $group : { _id : {"name": "$name","_id": "$_id" }, notes: { $push: "$notes" } } } ,
    {$project:{_id:0,"name":"$_id.name","_id":"$_id._id","notes":"$notes"}}])

对于C#使用MongoDB.Driver 1.9.0

public void GetData()
{
    IList<BsonDocument> Pipeline =new List<BsonDocument>();
    ///UnWind Query
    BsonDocument _oUnWind = new BsonDocument("$unwind", "$notes");
    Pipeline.Add(_oUnWind);
    ///Match Query
    IMongoQuery query = Query.NE("notes.title", "Hello MongoDB");
    Pipeline.Add(new BsonDocument("$match", query as BsonDocument));

    ///Group BY 
    IList<BsonElement> groupBYElement=new List<BsonElement>();
    IList<BsonElement> _id = new List<BsonElement>();
    _id.Add(new BsonElement("name", "$name"));
    _id.Add(new BsonElement("_id", "$_id"));
    groupBYElement.Add(new BsonElement("_id", new BsonDocument(_id)));
    groupBYElement.Add(new BsonElement("notes",new BsonDocument("$push","$notes")));
    BsonDocument _groupBy = new BsonDocument("$group", new BsonDocument(groupBYElement));
    Pipeline.Add(_groupBy);

    ///Project
    IList<BsonElement> ProjectElement = new List<BsonElement>();
    ProjectElement.Add(new BsonElement("_id", 0));
    ProjectElement.Add(new BsonElement("name", "$_id.name"));
    ProjectElement.Add(new BsonElement("_Id", "$_id._id"));
    ProjectElement.Add(new BsonElement("notes", "$notes"));
    BsonDocument _Project = new BsonDocument("$project", new BsonDocument(ProjectElement));
    Pipeline.Add(_Project);

    AggregateArgs _oAggregateArgs=new AggregateArgs();
    _oAggregateArgs.Pipeline =Pipeline;

    ///Mongo Database
    MongoDatabase _oMongoDatabase = MognoContext.GetDataBase();

    ///Final
    IList<BsonDocument> Result = _oMongoDatabase.GetCollection<ToTest>("ToTest").Aggregate(_oAggregateArgs).ToList();
    IList<ToTest> FinalResult = new List<ToTest>();
    foreach (BsonDocument itrBsonDocument in Result)
    {
        ToTest _oToTest= BsonSerializer.Deserialize<ToTest>(itrBsonDocument);
        FinalResult.Add(_oToTest);
    }
}