mongodb

how to find quickly all mongo documents having at least one element in an array


I have the following query

db.runCommand(
    {"text":"item","search":"\"price\" ",
     "project":{"_id":1},
     "limit":1,
     "filter":{"quotes":{"$not":{"$size":0}}}} 
);

But the filter part is taking a long time. For your understanding, "quotes" is a simple array of embeded documents. Is it possible to create an index to find all elements having at least one quote quickly?

EDIT: To be more specific: The question is not only about "how to query" but "how to make a useful index".


Solution

  • I think the quicker way is this one:

    db.collection.find({array: {$elemMatch: {$exists: true}}})