我是Mongodb&的新手。在我使用MEAN堆栈构建的Web应用程序中使用它。我的目标是通过连接它们并对它们应用过滤条件来查询两个表。例如:我有两张桌子 - Bike-BikeID,Registration No.,Make,Model&预约 - 约会日期,状态,自行车(ref自行车对象),我只想显示没有预约status ='Booked'的自行车。我想在Mongoose中完成以下SQL。
Select bike.* from Bike inner join Appointment on Bike.BikeID = Appointment.BikeID and Appointment.Status != 'Booked'
我正在使用以下代码,但我没有得到预期的结果。有人可以帮我解决这个问题。
app.get('/api/getbikeappo*',function(req,res){
var msg="";
//.find({cust:req.query._id})
//.populate('cust','email')
ubBike.aggregate([
{
$match:
{
cust : req.query._id
}
},
{
$lookup:
{
from: "appos",
localField: "_id",
foreignField: "bike",
as : "appointments"
}
},
{
$match:
{
"appointments" : {$eq : []}
}
}
])
.exec(function(err,bikes){
res.send(bikes);
if(err) throw err;
});
});
bikes - collection
{
"_id": {
"$oid": "57fb600fdd9070681de19c18"
},
"brand": "Splendor",
"model": "Splendor",
"year": "2002",
"kms": 0,
"regno": "TN02M8937",
"cust": {
"$oid": "57f8c44466cab97c1355a09a"
},
"__v": 0
}
{
"_id": {
"$oid": "57fb6025dd9070681de19c19"
},
"brand": "Activa",
"model": "Activa",
"year": "2016",
"kms": 0,
"regno": "TN14M3844",
"cust": {
"$oid": "57f8c44466cab97c1355a09a"
},
"__v": 0
}
appointment collection
----------------------
{
"_id": {
"$oid": "57fb6040dd9070681de19c1a"
},
"appoidt": {
"$date": "2016-10-15T18:30:00.000Z"
},
"reqdt": {
"$date": "2016-10-10T09:32:48.694Z"
},
"status": "Booked",
"bike": {
"$oid": "57fb600fdd9070681de19c18"
},
"cust": {
"$oid": "57f8c44466cab97c1355a09a"
},
"__v": 0
}
-----------------
Expected output is
{
"_id": {
"$oid": "57fb6025dd9070681de19c19"
},
"brand": "Activa",
"model": "Activa",
"year": "2016",
"kms": 0,
"regno": "TN14M3844",
"cust": {
"$oid": "57f8c44466cab97c1355a09a"
},
"__v": 0
}
答案 0 :(得分:2)
你几乎就在那里,你只需要正确的 $match
查询:
ubBike.aggregate([
{ "$match": { "cust": req.query._id } },
{
"$lookup": {
"from": "appos",
"localField": "_id",
"foreignField": "bike",
"as": "appointments"
}
},
{ "$match": { "appointments.status": { "$ne": "Booked" } } }
]).exec(function(err, bikes){
if(err) throw err;
res.send(bikes);
});