返回字段长度/大小的投影选项 [英] Projection option to return length/size of field

查看:25
本文介绍了返回字段长度/大小的投影选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想写一个像 SQL 一样的 mongo 查询:

I'm simply trying to write a mongo query like in SQL:

SELECT LENGTH(binaryBody) AS bodyLength FROM documents;

为此,我认为我必须使用 find 方法的投影.

To do so I thought I have to use the projection of the find method.

db.documents.find(
  {<query>},
  { bodyLength: {$size: 'body'}}
);

但是该怎么做呢?

错误:错误:{ "waitedMS" : NumberLong(0), "ok" : 0, "errmsg" :

Error: error: { "waitedMS" : NumberLong(0), "ok" : 0, "errmsg" :

"不支持的投影选项:bodyLength: { $size: "body" }",代码":2 }

"Unsupported projection option: bodyLength: { $size: "body" }", "code" : 2 }

推荐答案

.find() 不会以任何方式更改"返回的文档.您只能在投影中包含"或排除".

.find() does not "alter" documents returned in any way. You can only "include" or "exclude" in projection.

改变"的唯一内容是 .aggregate().mapReduce().

The only things that "alter" are .aggregate() or .mapReduce().

对于 .aggregate()$strLenCP$strLenBytes,但通常你的意思是前者:

For .aggregate(), requires MongoDB 3.4 for $strLenCP or $strLenBytes, but usually you mean the former:

db.documents.aggregate([
  { "$project": {
    "bodyLength": { "$strLenCP": "$body" }
  }}
])

对于.mapReduce()

db.documents.mapReduce(
  function() {
    emit(this._id, this.body.length)
  },
  function() { },
  { "out": { "inline": 1 } }
);

实际上,在后一种情况下,您可能还需要迭代光标,并且可能需要迭代,除非集合足够小,或者您实际上可以输出到另一个集合.

And realistically in the latter case, you may as well be iterating the cursor, and may need to unless the collection is small enough or you can actually output to another collection instead.

$size您尝试使用的运算符仅适用于数组"以返回存在的条目数.同样,它仅适用于 .aggregate() 方法.

如果您的意思是在字符串中省略 space 等字符,那么 $split$reduce$concat 可以应用:

If you mean to omit characters such as a space within a string then a $split and $reduce with $concat can be applied:

db.documents.aggregate([
  { "$addFields": {
    "bodyLength": {
      "$strLenCP": {
        "$reduce": {
          "input": { "$split": [ "$name", " "] },
          "initialValue": "",
          "in": { "$concat": [ "$$value", "$$this" ] }
        }
      }
    }
  }}
])

或者再次使用 mapReduce():

db.documents.mapReduce(
  function() {
    emit(this._id, "".concat.apply(this.body.split(" ")).length)
    // Or even
    // emit(this._id, this.body.split(" ").reduce((o,e) => o.concat(e),"").length)
  },
  function() { },
  { "out": { "inline": 1 } }
);

这篇关于返回字段长度/大小的投影选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆