重复的元素名称'PropertyName'Mongodb驱动程序C#异常

时间:2018-10-31 21:49:49

标签: c# mongodb

当我在Robo 3T中运行该查询时,该查询将起作用:

db.getCollection('groupSchedule').aggregate([{ "$match" : { "GroupId" : ObjectId("598dd346e5549706a80680bf") } }, 
{ "$lookup" : { "from" : "schedule", "localField" : "ScheduleIds", "foreignField" : "_id", "as" : "Schedule" } }, 
{ "$unwind" : "$Schedule" }, 
{ "$match" : {"$or": [{ "Schedule.End.ByDate" : {"$gte":new Date()}},{ "Schedule.End.ByDate" : null}] } }, 
{ "$group" : { "_id" : "$GroupId", "SurveyIds" : { "$addToSet" : "$Schedule.SurveyId" }, "ScheduleIds" : { "$addToSet" : "$Schedule._id" } } }, 
{ "$project" : { "_id" : 0, "SurveyIds" : 1, "ScheduleIds": 1 } }])

但是,当我尝试使用C#驱动程序执行相同的操作时,它炸毁了,说:

  

“重复的元素名称'Schedule.End.ByDate'。”,

代码如下:

return new List<BsonDocument>
{
    Common.Util.MongoUtils.Match(new BsonDocument { { "GroupId", groupId } }),
    Common.Util.MongoUtils.Lookup(scheduleCollections, "ScheduleIds", "_id", "Schedule"),
    Common.Util.MongoUtils.Unwind("$Schedule"),
    Common.Util.MongoUtils.Match(new BsonDocument
    {
        {
            "$or", new BsonDocument
            {
                {
                    "Schedule.End.ByDate", BsonNull.Value
                },
                {
                    "Schedule.End.ByDate", new BsonDocument
                    {
                        {
                            "$gte", DateTime.UtcNow
                        }
                    }
                }
            }
        }
    }),
    Group(),
    Common.Util.MongoUtils.Project(new BsonDocument
    {
        { "_id", 0 },
        { "SurveyIds", 1 },
        { "Schedules", 1 }
    })
};

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

通过将BsonDocument用于$or运算符,您正在有效地尝试创建以下内容:

"$or": {
    "Schedule.End.ByDate": null,
    "Schedule.End.ByDate": { "$gte" : ISODate("...") }
}

如果我们再次查看您的错误消息:

  

“重复的元素名称'Schedule.End.ByDate'。”,

很明显,您已经重复了Schedule.End.ByDate元素名称,这是无效的,而不是预期的。

相反,您想使用BsonArray包装两个分开的对象,以便产生您在Robo 3T查询中得到的结果。为此,您可以对C#代码进行以下修改:

"$or", new BsonArray
{
    new BsonDocument
    {
        { "Schedule.End.ByDate", BsonNull.Value }
    },
    new BsonDocument
    {
        {
            "Schedule.End.ByDate", new BsonDocument
            {
                { "$gte", DateTime.UtcNow }
            }
        }
    }
}

这将产生以下内容,与您对$or部分的Robo 3T查询相匹配:

{ "$or" : [
    { "Schedule.End.ByDate" : null },
    { "Schedule.End.ByDate" : { "$gte" : ISODate("...") } }
] }