0

I have an array of productIds and a Product collection. I want to query the product collection for all the products in the productIds array but I want the result to be in the same order as the query array. The productsIds are in a sorted order using other parameters which is not available in the documents in Products collection, so I cannot use a sort on product collection. Is there a way to preserve the order? Example:

productIds: [362,128,4783,1,44]

After db.collection('products'). find({id:{$in:productIds}}).toArray() I want the documents to be in the order as that of the productIds Currently I am getting a different order.

Community
  • 1
  • 1
Nidhin David
  • 2,426
  • 3
  • 31
  • 45

1 Answers1

0

You have two easy options:

1) Sort in-memory

const productIds = [362,128,4783,1,44];
const idAscending = (a, b) => productIds.indexOf(a.id) > productIds.indexOf(b.id);

db.collection('products').find({ id:{ $in:productIds } }).toArray()
.then(products => products.sort(idAscending));

2) Make separate queries

const Promise = require('bluebird');
const productIds = [362,128,4783,1,44];

Promise.map(productIds, db.collection('products').findOne);
broguinn
  • 591
  • 2
  • 14