Mongodb版本2.6.9
我试图计算一家公司参与消息传递互动的总数。我可以使用汇总$ group获得交互的一方,但我基本上看了两个字段,并将这些字段聚合在一起,为每个唯一的公司ID提供了空白。
sender_id
和receiver_id
与同一公司ID相关。
{ "_id" : a, "sender_id" : 1, "receiver_id" : 2, payload: "data" }
{ "_id" : b, "sender_id" : 2, "receiver_id" : 5, payload: "data" }
{ "_id" : c, "sender_id" : 2, "receiver_id" : 4, payload: "data" }
{ "_id" : d, "sender_id" : 3, "receiver_id" : 2, payload: "data" }
{ "_id" : e, "sender_id" : 4, "receiver_id" : 1, payload: "data" }
使用上述数据结构,我尝试生成类似于
的结果集{ "_id" : 1, count: 2}
{ "_id" : 2, count: 4}
{ "_id" : 3, count: 1}
{ "_id" : 4, count: 2}
{ "_id" : 5, count: 1}
例如,公司2涉及消息a,b,c,d。
答案 0 :(得分:1)
您的选项仅限于2.6管道。你可以尝试下面的管道。
<$group
$push
sender_id
为receiver_id
和$project
创建单值数组。
带有$setUnion
的 $unwind
将ID合并为单个数组。
$group
和db.collection.aggregate({
"$group": {
"_id": "$_id",
"sender_id": {
"$push": "$sender_id"
},
"receiver_id": {
"$push": "$receiver_id"
}
}
}, {
"$project": {
"id": {
"$setUnion": ["$sender_id", "$receiver_id"]
}
}
}, {
"$unwind": "$id"
}, {
"$group": {
"_id": "$id",
"count": {
"$sum": 1
}
}
})
计算出现次数。
[]
您可以使用以下管道获取更新版本。使用db.collection.aggregate({
$project: {
id: ["$sender_id", "$receiver_id"]
}
}, {
$unwind: "$id"
}, {
$group: {
_id: "$id",
count: {
$sum: 1
}
}
})
创建数组。
import java.util.Scanner;
public class DistanceFinder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x1 or <crtl + z> to quit");
while (input.hasNext()) {
double x1 = input.nextDouble();
System.out.println("Please input the x2 number:");
double x2 = input.nextDouble();
System.out.println("Please input the y1 number:");
double y1 = input.nextDouble();
System.out.println("Please input the y2 number:");
double y2 = input.nextDouble();
double x3 = 0;
double y3 = 0;
double xy1 = 0;
x3 = Math.pow((x2 - x1), 2);
y3 = Math.pow((y2 - y1), 2);
xy1 = x3 + y3;
double distance = Math.sqrt(xy1);
System.out.printf("Distance is %.6f %n%n%n", distance);
System.out.println("Enter x1 or <crtl + z> to quit");
}
input.close();
}
}