简体   繁体   中英

Get documents with at least two values for a especific condition in an Array, Query in MongoDB

Suppose that you have a collection in this structure .

{ "_id" : ObjectId("5f21a77c52efa009cc9857a7"), "results" : [ 76, 72, 93 ] },
{ "_id" : ObjectId("5f21a993b4d13477dd950904"), "results" : [ 90, 94, 80 ] },
{ "_id" : ObjectId("5f21a9a0b4d13477dd950905"), "results" : [ 70, 73, 99 ] },
{ "_id" : ObjectId("5f21a9abb4d13477dd950906"), "results" : [ 91, 85, 99 ] }

I am using Mongodb compass.

I would like to find the documents that their results array contain at least two items greater than 90.

I've tried doing this:

{$or:[{$and:[ {"results.0": { $gte : 90 } },{"results.1": { $gte : 90 } } ]}, {$and: [ {"results.1": { $gte : 90 } },{"results.2": { $gte : 90 } } ]}, {$and: [ {"results.0": { $gte : 90 } },{"results.2": { $gte : 90 } } ]}]}

With this query I get this result

I would like to know if there is "an optimized query" for doing the same thing! Thanks in advance!

You'll have to $filter the array to contain only matching items and then check it's size:

db.collection.aggregate([
  {
    $addFields: {
      tmp: {
        $filter: {
          input: "$results",
          as: "res",
          cond: {
            $gte: [
              "$$res",
              90
            ]
          }
        }
      }
    }
  },
  {
    $match: {
      "tmp.1": {
        $exists: true
      }
    }
  },
  {
    $project: {
      tmp: 0
    }
  }
])

MongoPlayground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM