如何获得最大的sections.Id在下面的文档中collection._id = some parameter
{
"_id" : ObjectId("571c5c87faf473f40fd0317c"),
"name" : "test 1",
"sections" : [
{
"Id" : 1,
"name" : "first section"
},
{
"Id" : 2,
"name" : "section 2"
},
{
"Id" : 3,
"name" : "section 3"
}
}
我在下面试过
db.collection.aggregate(
[
{
"$match": {
"_id": ObjectId("571c5c87faf473f40fd0317c")
}
},
{
"$group" : {
"_id" : "$_id",
"maxSectionId" : {"$max" : "$sections.Id"}
}
}
]);
但是不是返回max int单值,而是返回sections数组中所有Ids的数组。
在node.js中执行时,同样的查询返回一个空数组。
答案 0 :(得分:2)
对于opennig to package Hierarchies;
public static void generateHierarchy() {
Set<Entry<Long, Node>> iterator = graph.entrySet();
int i =0;
for(Entry<Long,Node> e : iterator) {
System.out.println(i++ +" - " +e.getValue().firstParents());
}
}
@SuppressWarnings({ "resource" })
public static void main(String[] args) throws JWNLException {
// TODO Auto-generated method stub
dictionary = Dictionary.getDefaultResourceInstance();
File dir = new File("C:/Users/D060891/Desktop/Thesis/sentencesNYT");
for (File file : dir.listFiles()) {
try {
BufferedReader input = new BufferedReader(new FileReader(file));
String line;
while ((line = input.readLine()) != null) {
demonstrateListHelper(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
generateHierarchy();
PrintStream out;
try {
out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
array
From nginx
Then change config
Cmd["nginx"]
添加您的聚合查询
$unwind
和您的重构聚合查询一样
"sections"
以及{$unwind : "$sections"}
的更多知识:https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/
答案 1 :(得分:2)
您可以使用简单的$project
阶段
类似this
db.collection.aggregate([
{ "$project": {
"maxSectionId": {
"$arrayElemAt": [
"$sections",
{
"$indexOfArray": [
"$sections.Id",
{ "$max": "$sections.Id" }
]
}
]
}
}}
])
答案 2 :(得分:0)
将$ group替换为$ project
In the $group stage, if the expression resolves to an array, $max does not traverse the array and compares the array as a whole.
With a single expression as its operand, if the expression resolves to an array, $max traverses into the array to operate on the numerical elements of the array to return a single value
[sic]