投影选项以返回字段的长度/大小 [英] Projection option to return length/size of field
问题描述
我只是想像在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()
方法一起使用.
The $size
operator you are attempting to use only applies to "arrays" to return the number of entries present. And again, it's only valid for usage with the .aggregate()
method.
如果您要在字符串中省略诸如space
之类的字符,则 $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屋!