Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-32947

Does mongodb $lookup operator ruins default array order?

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.4.10
    • Component/s: Aggregation Framework
    • None
    • ALL
    • Hide

      1. Get some test docs with array field, filled with ObjectId elements.
      2. Run this query.

      db.getCollection('trades').aggregate([
      {  '$match': {
              _id: ObjectId('5a546428f228c3156579fe00')
          } 
      }, 
      { 
          '$lookup': { 
              from: 'images',
              localField: 'images',
              foreignField: '_id',
              as: 'images'
          }
      }
      ]);
      

      3. Default order is ruined.

      Show
      1. Get some test docs with array field, filled with ObjectId elements. 2. Run this query. db.getCollection( 'trades' ).aggregate([ { '$match' : { _id: ObjectId( '5a546428f228c3156579fe00' ) } }, { '$lookup' : { from: 'images' , localField: 'images' , foreignField: '_id' , as: 'images' } } ]); 3. Default order is ruined.

      I faced with some strange things when I was working with mongoose. I got mongodb collection with some docs:

      {
      "_id" : ObjectId("5a0bf58c9616e5016426d5ef"),
      "categoryId" : 101,
      "name" : "Some name of something",
      "price" : 50000,
      "images" : [ 
          ObjectId("5a0bf5349616e5016426d5e9"),
          ObjectId("5a0bf6ac9616e5016426d5f7")
      ],
      }
      

      When I join images in "images" field by ObjectId, $lookup operator jumble up default order of array. Why is this happening? When I use third-party ODM (Mongoose) to join images default order of images array is preserved.

      db.getCollection('trades').aggregate([
      {  '$match': {
              _id: ObjectId('5a546428f228c3156579fe00')
          } 
      }, 
      { 
          '$lookup': { 
              from: 'images',
              localField: 'images',
              foreignField: '_id',
              as: 'images'
          }
      }
      ]);
      

            Assignee:
            mark.agarunov Mark Agarunov
            Reporter:
            penpaul Pavel
            Votes:
            0 Vote for this issue
            Watchers:
            11 Start watching this issue

              Created:
              Updated:
              Resolved: