1

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 ?

8
  • So according to this open ticket it's not implemented yet Commented Jan 10, 2018 at 12:54
  • But they have released 3+ version of drivers Commented Jan 10, 2018 at 12:56
  • 1
    its a really frustrating issue Commented Jan 10, 2018 at 12:56
  • What is your schema? Commented Jan 10, 2018 at 12:58
  • i have basically Two Collections Commented Jan 10, 2018 at 13:00

1 Answer 1

0

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'
}
Sign up to request clarification or add additional context in comments.

1 Comment

actually i just modified my functions and i put a extra __id field which is text

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.