1
如何將上面的sql子查詢轉換爲mongo聚合管道?select name,age from table1 where name in(select from table1 where age> 20)如何在mongo聚合管道中實現sql子查詢?
如何將上述sql子查詢轉換爲mongo聚合管道?
如何將上面的sql子查詢轉換爲mongo聚合管道?select name,age from table1 where name in(select from table1 where age> 20)如何在mongo聚合管道中實現sql子查詢?
如何將上述sql子查詢轉換爲mongo聚合管道?
考慮下面的示例數據:
db.collection.insert([
{ "name": "Peter", "age": 1 },
{ "name": "Peter", "age": 10 },
{ "name": "Peter", "age": 100 },
{ "name": "Paul", "age": 1 },
{ "name": "Mary", "age": 100 },
])
你可以做的是這樣的:
db.collection.aggregate({
$group: {
"_id": "$name", // group by name
"docs": { $push: "$$ROOT" } // push all found documents into an array per group
}
}, {
$match: {
"docs.age": { $gt: 5 } // eliminate all records that do not have at least one "age" entry that's greater than 5
}
}, {
$unwind: "$docs" // flatten the group structure into multiple documents again
}, {
$replaceRoot: {
"newRoot": "$docs" // restore original document layout
}
})
...這將產生:
/* 1 */
{
"_id" : ObjectId("59df15f9ad526e347ed9cda0"),
"name" : "Mary",
"age" : 100.0
}
/* 2 */
{
"_id" : ObjectId("59df15f9ad526e347ed9cd9c"),
"name" : "Peter",
"age" : 1.0
}
/* 3 */
{
"_id" : ObjectId("59df15f9ad526e347ed9cd9d"),
"name" : "Peter",
"age" : 10.0
}
/* 4 */
{
"_id" : ObjectId("59df15f9ad526e347ed9cd9e"),
"name" : "Peter",
"age" : 100.0
}
你能不能給我們一些樣品數據?和所需的JSON輸出,請。 – dnickless