一、mongodb的使用:
1、聚合一般格式:
db.orders.aggregate([
{
$lookup: {
from: "items",
localField: "item", // field in the orders collection
foreignField: "item", // field in the items collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
])
2、数据样例:
db.books.drop();
db.books.insert({_id:1,name:'book1',author:[1,2]});
db.books.insert({_id:2,name:'book2',author:1});
db.books.insert({_id:3,name:'book3',author:2});
db.books.insert({_id:4,name:'book4'});
db.authors.drop();
db.authors.insert({_id:1,name:'john',nationality:'cn'});
db.authors.insert({_id:2,name:'Mark',nationality:'us'});
db.authors.insert({_id:3,name:'Shakespeare',nationality:'un'})
3、查出所有的《作者及作者的图书们》(不包括作者的_id,图书_id,图书的作者_id)
db.authors.aggregate([{$lookup:{from:'books',localField:'_id',foreignField:'author',as:'books'}},{$project:{_id:0,'books._id':0,'books.author':0}}]);
结果:
{ "name" : "john", "nationality" : "cn", "books" : [ { "name" : "book1" }, { "name" : "book2" } ] }
{ "name" : "Mark", "nationality" : "us", "books" : [ { "name" : "book1" }, { "name" : "book3" } ] }
{ "name" : "Shakespeare", "nationality" : "un", "books" : [ ] }
4、查出所有的 《图书及图书的作者们》,不包括:图书的_id,作者的_id
db.books.aggregate([{$lookup:{from:'authors',localField:'author',foreignField:'_id',as:'author'}},{$project:{_id:0,'author._id':0}}]);
结果:
{ "name" : "book1", "author" : [ { "name" : "john", "nationality" : "cn" }, { "name" : "Mark", "nationality" : "us" } ] }
{ "name" : "book2", "author" : [ { "name" : "john", "nationality" : "cn" } ] }
{ "name" : "book3", "author" : [ { "name" : "Mark", "nationality" : "us" } ] }
{ "name" : "book4", "author" : [ ] }
二、mongoose的populate使用:
根据【一.2】的数据,我们编写下代码,进行关联查询
const mongoose=require('mongoose')
const Schema=mongoose.Schema;
mongoose.connect('mongodb://localhost/test2',{ useNewUrlParser: true,useUnifiedTopology: true })
const bookSchema=Schema({
_id:Number,
name:String,
author:[{type:Number,ref:'Author'}]
})
const authorSchema=Schema({
_id:Number,
name:String,
nationality:String
})
const Author=mongoose.model('Author',authorSchema)
const Book=mongoose.model('Book',bookSchema)
Book.find({})
.populate('author')
.exec()
.then(books=>{
console.log(books)
})
.catch(err=>console.log(err))
.finally(()=>mongoose.disconnect())