Query for documents where array size is greater than 1

后端 未结 14 1837
北海茫月
北海茫月 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:18

    I found this solution, to find items with an array field greater than certain length

    db.allusers.aggregate([
      {$match:{username:{$exists:true}}},
      {$project: { count: { $size:"$locations.lat" }}},
      {$match:{count:{$gt:20}}}
    ])
    

    The first $match aggregate uses an argument thats true for all the documents. If blank, i would get

    "errmsg" : "exception: The argument to $size must be an Array, but was of type: EOO"
    
    0 讨论(0)
  • 2020-11-22 03:19

    None of the above worked for me. This one did so I'm sharing it:

    db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )
    
    0 讨论(0)
  • 2020-11-22 03:22

    You can MongoDB aggregation to do the task:

    db.collection.aggregate([
      {
        $addFields: {
          arrayLength: {$size: '$array'}
        },
      },
      {
        $match: {
          arrayLength: {$gt: 1}
        },
      },
    ])
    
    0 讨论(0)
  • 2020-11-22 03:23

    Try to do something like this:

    db.getCollection('collectionName').find({'ArrayName.1': {$exists: true}})
    

    1 is number, if you want to fetch record greater than 50 then do ArrayName.50 Thanks.

    0 讨论(0)
  • 2020-11-22 03:25
    db.accommodations.find({"name":{"$exists":true, "$ne":[], "$not":{"$size":1}}})
    
    0 讨论(0)
  • 2020-11-22 03:27

    MongoDB 3.6 include $expr https://docs.mongodb.com/manual/reference/operator/query/expr/

    You can use $expr in order to evaluate an expression inside a $match, or find.

    { $match: {
               $expr: {$gt: [{$size: "$yourArrayField"}, 0]}
             }
    }
    

    or find

    collection.find({$expr: {$gte: [{$size: "$yourArrayField"}, 0]}});
    
    0 讨论(0)
提交回复
热议问题