Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $lookup dynamic collection

I have following schema where the item type might vary, and is mentioned in connections.kind.

var userSchema = new Schema({
  name: String,
  connections: [{
    kind: String,
    item: { type: ObjectId, refPath: 'connections.kind' }
  }]
});

var organizationSchema = new Schema({ name: String });

I am trying to do a dynamic lookup so that the item object is populated. But this doesn't seem to work.

db.users.aggregate([
    {
        $lookup:{
            from: '$connections.kind',
            localField: 'connections.item',
            foreignField: '_id',
            as: 'items'
        }
    }
])

I know I can do it with mongoose.populate, but want to know if it is possible with $lookup

like image 977
sidgate Avatar asked Oct 06 '16 18:10

sidgate


1 Answers

As of now, you can't. The from field cannot be an expression and must be a string literal. However, there is an open issue which you can track here that appears to be exactly what you need: https://jira.mongodb.org/browse/SERVER-22497.

like image 78
Andrew Wei Avatar answered Oct 03 '22 06:10

Andrew Wei