Change type of field inside mongoDB aggregation and does $lookup utilises index on fields or not?

前端 未结 2 1723
情歌与酒
情歌与酒 2020-12-10 23:43

I am performing joins in mongodb using $lookup, now i am facing a problem here. I have two collections first one to contains users all bookmarks brands and the second one co

相关标签:
2条回答
  • 2020-12-11 00:14

    You cannot convert the string to a object Id within the pipeline, you'll have to go though each document and convert it manually, using something like (you shouldnt be storing a mix match of types anyway, so it's probably worth updating in the long run):

    how to convert string to numerical values in mongodb

    as for does $lookup use index, If you look at the stats from this blog you'll see that indexes are used -

    http://guyharrison.squarespace.com/blog/2016/7/4/join-performance-in-mongodb-32-using-lookup.html

    0 讨论(0)
  • 2020-12-11 00:15

    Try casting your brands to ObjectIds before your population:

    user_bookmarked.brands.map((brand) => return mongoose.Types.ObjectId(brand) )
    

    But you really should consider storing them as refs instead, your model should look something like:

    const user_bookmarked = new mongoose.Schema({
        ...
        brands: [{type: mongoose.Schema.Types.ObjectId, ref: 'Brands'}],
        ...
        })
    

    This way they will be ObjectIds from the start.!

    Regarding the second question this post explains it I think: join-performance-in-mongodb-32-using-lookup

    0 讨论(0)
提交回复
热议问题