[英]How can I count items in mongo collection that have intersecting subcollections?
For every item in my collection I need to find count of other items that have intersecting subcollections.对于我的集合中的每个项目,我需要找到具有交叉子集合的其他项目的数量。 For example, given this collection
例如,给定这个集合
[{id:1,"sub":[1, 2, 3]},
{id:2,"sub":[2, 3, 4]},
{id:3,"sub":[4, 5, 6],
{id:4,"sub":[7, 8, 9]}]
expected result is预期结果是
[{id:1,"count":1},
{id:2,"count":2},
{id:3,"count":1},
{id:4,"count":0"}]
Starting with the algorithm in pure MongoDB query language: You have to restructure your documents so that each document contains it's initial sub
array and an array of all the other sub
values.从纯 MongoDB 查询语言中的算法开始:您必须重构文档,以便每个文档都包含它的初始
sub
数组和所有其他sub
值的数组。 To do that you need to run $group along with $unwind .为此,您需要将$group与$unwind一起运行。 Then it becomes easy to just run $map with $setIntersect $filter out all empty and equal to self arrays and get the size using $size
然后很容易只运行$map和$setIntersect $filter 过滤掉所有空的和等于 self 的数组并使用$size获取大小
db.collection.aggregate([
{
$group: {
_id: null,
current: { $push: "$$ROOT" },
all: { $push: "$sub" }
}
},
{
$unwind: "$current"
},
{
$project: {
id: "$current.id",
count: {
$size: {
$filter: {
input: {
$map: {
input: "$all",
in: { $setIntersection: [ "$$this", "$current.sub" ] }
}
},
cond: {
$and: [
{ $ne: [ "$$this", [] ] },
{ $ne: [ "$$this", "$current.sub" ]}
]
}
}
}
}
}
}
])
Since the aggregation is quite complex there's no point in running it in a strongly-typed way in C#.由于聚合非常复杂,因此在 C# 中以强类型方式运行它是没有意义的。 All you can do is to use
BsonDocument
class to build your pipeline like:您所能做的就是使用
BsonDocument
类来构建您的管道,例如:
var groupDef = new BsonDocument()
{
{ "_id", "" },
{ "current", new BsonDocument(){ { "$push", "$$ROOT" } } },
{ "all", new BsonDocument(){ { "$push", "$sub" } } },
};
var projectDef = BsonDocument.Parse(@"{
id: ""$current.id"",
_id: 0,
count: {
$size: {
$filter: {
input: {
$map: {
input: ""$all"",
in: {
$setIntersection: [
""$$this"",
""$current.sub""
]
}
}
},
cond: {
$and: [
{
$ne: [
""$$this"",
[]
]
},
{
$ne: [
""$$this"",
""$current.sub""
]
}
]
}
}
}
}
}");
var result = mongoDBCollection.Aggregate()
.Group(groupDef)
.Unwind("current")
.Project(projectDef)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.