【问题标题】:How to find the document in mongodb where array size is greater than 1如何在mongodb中找到数组大小大于1的文档
【发布时间】:2020-12-12 17:38:03
【问题描述】:

我想查找所有存在且数组大小大于 1 的文档

我的 MongoDB 集合看起来像

{
  "_id" : ObjectId("5eaaeedd00101108e1123452"),
  "type" : ["admin","teacher","student"]
}
{
  "_id" : ObjectId("5eaaeedd00101108e1123453"),
  "type" : ["student"], 
}

我如何找到超过 1 种类型的文档

【问题讨论】:

  • 从 MongoDB 4.4 开始,$where 不再支持已弃用的带作用域的 BSON 类型 JavaScript(即 BSON 类型 15)。从版本 4.2.1 开始,不推荐使用带有 $where 函数范围的 JavaScript。 Ref docs.mongodb.com/manual/reference/operator/query/where 所以当你升级你的版本时,它不会工作

标签: javascript node.js arrays mongodb express


【解决方案1】:
db.collection.find({type: {$gt: 1}})

只需更改集合的名称


gt表示更伟大,你可以看到更多关于它here

【讨论】:

    【解决方案2】:

    你可以做这样的事情。这是工作版本> 4.2

    db.collection.find({
          $expr: {
            $gt: [
              {
                $size: "$type"
              },
              1
            ]
          }
        })
    

    工作Mongo playground

    如果你用得少,你可以做一些类似的事情

    db.collection.find({
      type: {
        $gt: {
          $size: 1
        }
      }
    })
    

    【讨论】:

      【解决方案3】:
      1. 您可以使用$gt

      db.collectionName.find({"type": {$gt: 1} });

      1. 您可以使用$where

      db.collectionName.find( { $where: "type > 1" } );

      【讨论】:

        【解决方案4】:

        这个问题唯一可行的解​​决方案如下:

        db.collection.find({
          $expr: {
            $gt: [
              {
                $size: "$arrayfield"
              },
              1
            ]
          }
        })
        

        所有其他解决方案都不起作用。试过了。

        【讨论】:

          猜你喜欢
          • 2021-02-17
          • 2020-11-18
          • 2011-12-10
          • 1970-01-01
          • 2013-06-01
          • 2012-05-13
          相关资源
          最近更新 更多