一、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桩了、數(shù)據(jù)樣例:
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附帽、查出所有的《作者及作者的圖書(shū)們》(不包括作者的_id,圖書(shū)_id,圖書(shū)的作者_(dá)id)
db.authors.aggregate([{$lookup:{from:'books',localField:'_id',foreignField:'author',as:'books'}},{$project:{_id:0,'books._id':0,'books.author':0}}]);
結(jié)果:
{ "name" : "john", "nationality" : "cn", "books" : [ { "name" : "book1" }, { "name" : "book2" } ] }
{ "name" : "Mark", "nationality" : "us", "books" : [ { "name" : "book1" }, { "name" : "book3" } ] }
{ "name" : "Shakespeare", "nationality" : "un", "books" : [ ] }
4、查出所有的 《圖書(shū)及圖書(shū)的作者們》圣猎,不包括:圖書(shū)的_id,作者的_id
db.books.aggregate([{$lookup:{from:'authors',localField:'author',foreignField:'_id',as:'author'}},{$project:{_id:0,'author._id':0}}]);
結(jié)果:
{ "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使用:
根據(jù)【一.2】的數(shù)據(jù),我們編寫(xiě)下代碼送悔,進(jìn)行關(guān)聯(lián)查詢
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())