0

I have two collections:

Annotations

{
  annotations: ["lion", "zebra", "cobra"],
  imagesId: 1234
}

{
  annotations: ["lion", "zebra", "cobra", "dog"],
  imagesId: 12345
}  

Images

{_id:1234,
 name: "africa"
}
{_id:12345,
 name: "america"
}  

I want to find all image names annotated with for example zebra.

This is my pseudo approach:

let annotations = Annotations.find({annotations: {'$in': 'zebra'}});  

getOnlyUniqueItems(annotations);  

Images.find({_id: {'$in': annotations}});  

It will work, problem is when annotations contain for example 1M ids, then query itself will be more then 1MB of text, it will probably kill my database.

Question: what is the best approach to this problem?
Thank you! :-)

Jacek Wojcik
  • 1,223
  • 2
  • 19
  • 33

1 Answers1

1

If we won't take in consideration that save annotations as a free text separated by , is a bad idea, and performance/response time are not issue for the specific use case you might give a try to $lookup, something like:

Annotations.aggregate([
  { $match: { annotations: { '$in': 'zebra' } } },
  {
      $lookup:
         {
            from: "Images",
            localField: "imagesId",
            foreignField: "_id",
            as: "image"
        }
   }
]);
zooblin
  • 2,172
  • 2
  • 27
  • 33