Query for documents where array size is greater than 1

后端 未结 14 2149
北海茫月
北海茫月 2020-11-22 03:02

I have a MongoDB collection with documents in the following format:

{
  \"_id\" : ObjectId(\"4e8ae86d08101908e1000001\"),
  \"name\" : [\"Name\"],
  \"zipcod         


        
14条回答
  •  独厮守ぢ
    2020-11-22 03:40

    There's a more efficient way to do this in MongoDB 2.2+ now that you can use numeric array indexes in query object keys.

    // Find all docs that have at least two name array elements.
    db.accommodations.find({'name.1': {$exists: true}})
    

    You can support this query with an index that uses a partial filter expression (requires 3.2+):

    // index for at least two name array elements
    db.accommodations.createIndex(
        {'name.1': 1},
        {partialFilterExpression: {'name.1': {$exists: true}}}
    );
    

提交回复
热议问题