Arj*_*ava 7 mongodb mongodb-query aggregation-framework
我有两个集合:
学生
{
_id: ObjectId("657..."),
name:'abc'
},
{
_id: ObjectId("593..."),
name:'xyz'
}
Run Code Online (Sandbox Code Playgroud)
图书馆
{
_id: ObjectId("987..."),
book_name:'book1',
issued_to: [
{
student: ObjectId("657...")
},
{
student: ObjectId("658...")
}
]
},
{
_id: ObjectId("898..."),
book_name:'book2',
issued_to: [
{
student: ObjectId("593...")
},
{
student: ObjectId("594...")
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个 Join to Student集合,该集合存在于Library集合的对象字段的issue_to数组中。
我想对学生收藏进行查询以获取学生数据以及图书馆收藏,如果学生存在或不存在,它将检查issued_to数组,否则获取图书馆文档。我试过 $lookup of mongo 3.6 但我没有成功。
db.student.aggregate([{$match:{_id: ObjectId("593...")}}, $lookup: {from: 'library', let: {stu_id:'$_id'}, pipeline:[$match:{$expr: {$and:[{"$hotlist.clientEngagement": "$$stu_id"]}}]}])
Run Code Online (Sandbox Code Playgroud)
但它会引发错误,请在这方面帮助我。我还查看了在 stackoverflow 上提出的其他问题,例如。上计算器问题, 对问题2计算器但这些comapring简单字段不是对象的数组。请帮我
我不确定我完全理解你的问题,但这应该对你有帮助:
db.student.aggregate([{
$match: { _id: ObjectId("657...") }
}, {
$lookup: {
from: 'library',
localField: '_id' ,
foreignField: 'issued_to.student',
as: 'result'
}
}])
Run Code Online (Sandbox Code Playgroud)
如果您只想获取book_name每个学生的所有信息,您可以这样做:
db.student.aggregate([{
$match: { _id: ObjectId("657657657657657657657657") }
}, {
$lookup: {
from: 'library',
let: { 'stu_id': '$_id' },
pipeline: [{
$unwind: '$issued_to' // $expr cannot digest arrays so we need to unwind which hurts performance...
}, {
$match: { $expr: { $eq: [ '$issued_to.student', '$$stu_id' ] } }
}, {
$project: { _id: 0, "book_name": 1 } // only include the book_name field
}],
as: 'result'
}
}])
Run Code Online (Sandbox Code Playgroud)