Search code examples
mongodbaggregation-frameworkmongodb-.net-driver

How to do a lookup between string field and ObjectId - MongoDB C# Driver


I have these collections:

1 - Order:

{ 
    "_id" : ObjectId("5ac68963b305462bc88150f6"), 
    "ClientId" : "5aabc24bb3054633a4053a9f" 
}

2 - Client:

{ 
    "_id" : ObjectId("5aabc24bb3054633a4053a9f"), 
    "Name" : "Tiago", 
    "Email" : "tiago@email.com", 
}

I want to bring in Order, the data from Client. But because ClientId is a string and the _id in Client is an ObjectId I can't do the lookup between then.

I'm doing with MongoDB C# Driver, this is my code until now:

var order = _database.GetCollection<Order>.Aggregate().Match(myFilter).Lookup("Client", "ClientId", "_id", "MyPropertyToFill").As<Order>().FirstOrDefault();

Any idea about how to do this?


Solution

  • In your model, you have to define iClientId as an ObjectId as follow:

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema
    
    const Order = new Schema({
      iClientId: Schema.Types.ObjectId
      // Rest of the Field
    })
    
    module.exports = mongoose.model('order', Order)
    

    Now In your file where you want to do a lookup

    const mongoose = require('mongoose')
    const ObjectId = mongoose.Types.ObjectId
    
    Model.aggregate([
      {$match: {_id: ObjectId('filter_id')}},
      {$lookup: {
        from: 'client',
        localField: 'ClientId',
        foreignFiled: '_id',
        as: 'fromclient'
      }}
    ], (err, result) => {
     // Your action
    })
    

    This how you can achieve that, I have done it with mongoose but you can do it without mongoose as well.