//演示插入的表结构
db.getCollection('tmp_article_user').insertMany([{
name: 'admin',
age:18
},
{
name: 'xiaomin',
age:19
}]);
db.getCollection('tmp_article').insertMany([{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'admin',
likes: 100
},
{
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'xiaomin',
likes: 10
}])
///单表查询
db.getCollection('tmp_article').aggregate([
{$match:{}},
{$facet:{
total: [{ $count:"count" }],
rows:[{ $skip:0 },{ $limit: 3}]
}
},
{
$project: {
data:"$rows",
total: {$arrayElemAt: [ "$total.count", 0 ]},
}
}
]);
//多表关联查询
db.getCollection('tmp_article').aggregate([
{$match:{}},
{$lookup:{
from: "tmp_article_user",
localField: "by_user", // field in the orders collection
foreignField: "name", // field in the items collection
as: "user_info"
}
},
{$facet:{
total: [{ $count:"count" }],
rows:[{ $skip:0 },{ $limit: 3}]
}
},
{
$project: {
data:"$rows",
total: {$arrayElemAt: [ "$total.count", 0 ]},
}
}
]);
//多表多条件关联查询
db.getCollection('tmp_article').aggregate([
{$match:{}},
{$lookup:{
from: "tmp_article_user",
let: { user_name: "$by_user" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[{ $eq: [ "$name","$$user_name" ] }]
}
}
},
],
as: "user_info"
}
},
{$facet:{
total: [{ $count:"count" }],
rows:[{ $skip:0 },{ $limit: 3}]
}
},
{
$project: {
data:"$rows",
total: {$arrayElemAt: [ "$total.count", 0 ]},
}
}
]);