如何使用Linq进行聚合查询。我知道有一个@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// Locatio-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
接口。但是当我进行聚合时似乎会抛出错误。
如果我有一个名为AsQueryable()
的集合,则存储如下数据:
person
和另一个名为 {
"Name": "Punny",
"Interests": [
1,
2
]
}
的集合存储如下数据:
interests
我想得到这样的东西:
{
"_id":1,
"name":"music"
},
{
"_id":2,
"name":"read"
}
如何通过Linq to {
"Name": "Punny",
"Interests": [
"music",
"read"
]
}
实现这一目标?
我试过这个:
AsQueryable
抛出_context.People.AsQueryable()
.Select(p => new
{
Name = p.Name,
Interests = p.InterestingIds
.Join(_context.Interests.AsQueryable(),
per => per,
i => i.Id,
(per, i) => new {i.Name})
}).ToList();
System.NotSupportedException:表达式树{document} {InterestingIds}中不支持类型System.Linq.Enumerable的连接.Join([FunnyMongoBlog.interest],per => per,i => i.Id ,(per,i)=> new<> f__AnonymousType1`1(Name = i.Name))。
我尝试了两次数据库:
System.NotSupportedException
这是有效的,但我想知道我们是否可以通过一次旅行来完成,以便数据库可以处理聚合。
答案 0 :(得分:0)
您可以在聚合框架中执行此操作,但我建议在mongoDB中使用subDocumnets的强大功能,并将这些元素完全嵌入到主文档中。换句话说,我们需要从关系思维转向文档思维。
我建议的物体形状:
{
"Name" : "Punny",
"Interests" : [{
"_id" : 1,
"name" : "music"
}, {
"_id" : 2,
"name" : "read"
}
]
}
在c#代码中
class MyClass {
public string Name;
public List < Interest > Interests;
}
class Interest {
public int Id;
public string Name;
}
现在请找到所要求的转换所需的bson文件:
db.col.aggregate([{
$unwind : "$Interests"
}, {
$lookup : {
from : "interests",
localField : "Interests",
foreignField : "_id",
as : "interest"
}
}, {
// now we need to reshape document
$project : {
_id : 1,
Name : 1,
Interests : "$interest.name"
}
},
//group documents back
{
$group : {
_id : {
id : "$_id",
name : "$Name"
},
Interests : {
$push : "$Interests"
}
}
}, {
//final reshape
_id : "$_id.id",
Name : "$_id.name",
Interests : 1
}
])
并决定嵌入是否值得一试: - )
欢迎任何评论!