根据 Pymongo 中的值长度查询集合和文档

Des*_*wal 2 python mongodb pymongo mongodb-query pymongo-3.x

假设我的数据库给了我一个查询结果:

{'_id': ObjectId('5c99d76a32aacf180485c3b3'),
 'text': 'ILLUSTRATION : 1\nFind the quotient and remainder q and r for the pairs of positive integers given below:\n(i) 23,4\n(ii) 81,3\n(iii) 12,5\nUTION.\n',
 'text2': '',
 'parent': None,
 'repost': 3,
 'time': datetime.datetime(2010, 5, 9, 16, 5, 27, 838000)}
Run Code Online (Sandbox Code Playgroud)

我想获取前 1000 个文档,其中长度text或长度text2>=5:

我可以通过 Python 做到这一点,但这样做会很愚蠢:

objects = []
i = 0
for obj in db.essays.find():
    if len(obj['text']>=5) or len(obj['text2']>=5):
        objects.append(obj)
        i+=1
    if i==1000:
        break
Run Code Online (Sandbox Code Playgroud)

我知道这太愚蠢了。

limit(1000)如果我有完全匹配,我可以使用,但我不知道如何根据值长度获取文档。

编辑:不知何故我设法做一个补丁

{ "$or":[{"$expr": { "$gt": [ { "$strLenCP": "$text" }, 5 ]}},
                                     {"$expr": { "$gt": [ { "$strLenCP": "$text2" }, 5 ]}},
                                    {"$expr": { "$gt": [ { "$strLenCP": "$text3" }, 5 ]}},
                                     ]}
Run Code Online (Sandbox Code Playgroud)

但是当我使用该AND操作在所有文本长度小于 3 的情况下获取文档时,它会引发错误:

{ "$and":[{"$expr": { "$lt": [ { "$strLenCP": "$text" }, 5 ]}},
                                     {"$expr": { "$lt": [ { "$strLenCP": "$text2" }, 5 ]}},
                                    {"$expr": { "$lt": [ { "$strLenCP": "$text3" }, 5 ]}},
                                     ]}
Run Code Online (Sandbox Code Playgroud)

它可以使用limit(2)但失败 >2 并抛出错误:

`OperationFailure: $strLenCP requires a string argument, found: null`
Run Code Online (Sandbox Code Playgroud)

Tom*_*ert 5

您可以使用带有strLenCP的管道

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$or": [
          {
            "$gte": [
              {
                "$strLenCP": {
                  "$ifNull": [
                    "$text",
                    ""
                  ]
                }
              },
              5
            ]
          },
          {
            "$gte": [
              {
                "$strLenCP": {
                  "$ifNull": [
                    "$text2",
                    ""
                  ]
                }
              },
              5
            ]
          }
        ]
      }
    }
  },
  {
    "$limit": 1000
  }
])
Run Code Online (Sandbox Code Playgroud)

但是,如果您真的关心以上性能,最好的方法是预处理该信息:

{
'_id': ObjectId('5c99d76a32aacf180485c3b3'),
 'text': 'ILLUSTRATION : 1\nFind the quotient and remainder q and r for the pairs of positive integers given below:\n(i) 23,4\n(ii) 81,3\n(iii) 12,5\nUTION.\n',
 'text2': '',
 'parent': None,
 'repost': 3,
 'time': datetime.datetime(2010, 5, 9, 16, 5, 27, 838000),
  'text_len': 100,
  "text2_len": 0
}
Run Code Online (Sandbox Code Playgroud)

所以现在一个简单的查询就足够了:

db.essays.find({"$or": [{"text_len": {"$gte": 5}}, {"text2_len": {"$gte": 5}}]}).limit(1000)
Run Code Online (Sandbox Code Playgroud)

蒙戈游乐场