我正在尝试通过一些属性过滤mongo结果,然后根据属性Name对它们进行分组。任何帮助都将不胜感激。
这是我的mongo收藏品:
[
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 10,
Value: 20
},
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 1000,
Value: 2000
},
{
Name: "test2",
Type: "typeX"
Date: "10-10-10",
Age: 20,
Value: 30
},
{
Name: "test3",
Type: "typeX"
Date: "10-10-10",
Age: 30,
Value: 40
}
]过滤步骤:if Date = "10-10-10"和Type = "typeX"以及Name $in ["test1", "test2"]。这一步工作正常,我能够过滤结果。
[
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 10,
Value: 20
},
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 1000,
Value: 2000
},
{
Name: "test2",
Type: "typeX"
Date: "10-10-10",
Age: 20,
Value: 30
}
]按Name对过滤结果分组:此步骤不起作用。
{
"test1": [
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 10,
Value: 20
},
{
Name: "test1",
Type: "typeX"
Date: "10-10-10",
Age: 1000,
Value: 2000
}
],
"test2": [
{
Name: "test2",
Type: "typeX"
Date: "10-10-10",
Age: 20,
Value: 30
}
]
}以下是我到目前为止的代码。我真的想避免使用lambda表达式,因为每当我尝试它时,我都会看到大量的性能损失。
public Dictionary<string, List<DummyClass>> FilterAndGroupBy(string type, string date, List<string> names)
{
// Get the collection
var collection = GetDummyCollection();
var filter = new BsonDocument
{
{"Date", date},
{"Type", type}
};
// Create the filter
filter.Add("Name", new BsonDocument
{
{"$in", new BsonArray(indexNames)}
});
// Create the group, this does not work.
var group = new BsonDocument
{
{"_id",
new BsonDocument {
{"Name", "$Name"},
{"Result", new BsonDocument("$push", new BsonArray()) }
}
}
};
// Query the group with the filter
var resultslambda = collection.Aggregate().Match(filter).Group(group).ToList();
return new Dictionary<string, List<DummyClass>>();
}发布于 2018-01-21 21:03:17
以下是您的数据的有效组表达式:
{
$group :
{
_id : "$Name"
Result: { $push: {
Name: "$Name",
Type: "$Type",
Date: "$Date",
Age: "$Age",
Value: "$Value",
}
}
},
}如您所见,您错误地将$push累加器放在了expression for _id字段中。
下面是创建分组的正确语句:
var group = new BsonDocument
{
{
"_id", new BsonDocument {
{"Name", "$Name"},
}
},
{
"Result", new BsonDocument("$push", new BsonDocument
{
{ "Name", "$Name" },
{ "Type", "$Type" },
{ "Date", "$Date" },
{ "Age", "$Age" },
{ "Value", "$Value" },
}
)
}
};我也怀疑你在使用lambda表达式时关于性能损失的说法。在这两种情况下,MongoDB驱动程序都将向服务器发送相同的查询。因此,我不知道在您的情况下性能下降的原因是什么。另一方面,像现在这样使用BsonDocument构建查询,可能会导致不易识别的错误。你的问题就是证据。因此,我建议重新检查性能指标。如果你仍然有退化的证据,那么可能值得单独发布关于这个问题的问题。
为了以防万一,下面是基于lambdas的分组的模拟:
var resultslambda = collection.Aggregate().Match(filter).Group(
x => x.Name,
g => new {
Result = g.Select(x => new
{
x.Name,
x.Type,
x.Date,
x.Age,
x.Value
})
}
).ToList();https://stackoverflow.com/questions/48359797
复制相似问题