1

我是Mongodb &的新手,在使用MEAN堆栈构建的Web应用程序中使用它。我的目标是通过连接它们并在它们上应用过滤条件来查询两个表。例如:我有两张桌子 - 自行车BikeID,注册号,品牌,型号&约会 - 约会日期,状态,自行车(参考自行车对象),我只想显示那些没有预约状态= “预订”。我想在Mongoose中完成以下SQL。在Mongoose中查询连接和过滤器

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

后您的文件的样本,并输出你期待? –

+0

@ClementAmarnath完成 –

回答

1

你几乎没有,你只需要跟随正确的$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);  
}); 
+0

谢谢@chridam。有用!! –