简体   繁体   中英

How to use ObjectId in $lookup using mongodb nodejs drivers

Please help me to find out a suitable solution

collection were users details are stored app_users

{
  _id: {
    $oid: "abcd1235a6ad4a56dadasd"
  },
  user_name: "vikas Kandari",
  user_dp: "ASDAD486412.jpg"
}

collection where users bookings are stored bookings

{
  _id : {
    $oid : "asdasdasdasdasd"
  },
  user_id : "abcd1235a6ad4a56dadasd",
  booking_item : "some product",
  booking_date : "datetime"
}

Lookup(left Join) query i am using is

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://root:root@localhost:3000/app';
const dbName = 'app';
MongoClient.connect(url, function(err, client) {
  assert.equal(err, null);
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  const collection = db.collection('users');
  collection.aggregate([{
    $lookup: {
      from: 'bookings',
      localField: '_id',
      foreignField: 'user_id',
      as: 'bookings'
    }
  }]).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log(docs);
  });
  client.close();
});

I want to select bookings with there corresponding user details from users collections but Its returning blank because mongodb is comparing string with objectId so is there any way to perform this task ?

Add This before the lookup

$project:{
    $let:
        {
         vars: { id:'_id.$oid' },
         in: ObjectId("$$id")
         }
}

Change to

$lookup: {
  from: 'bookings',
  localField: '_id.$oid',
  foreignField: 'user_id',
  as: 'bookings'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM