.find()
不会以任何方式“更改”返回的文档。您只能在投影中“包含”或“排除”。
唯一“改变”的是.aggregate() or .mapReduce().
For .aggregate()
,需要 MongoDB 3.4$strLenCP or $strLenBytes,但通常你指的是前者:
db.documents.aggregate([
{ "$project": {
"bodyLength": { "$strLenCP": "$body" }
}}
])
For .mapReduce()
db.documents.mapReduce(
function() {
emit(this._id, this.body.length)
},
function() { },
{ "out": { "inline": 1 } }
);
实际上,在后一种情况下,您可能还需要迭代游标,并且可能需要这样做,除非集合足够小或者您实际上可以输出到另一个集合。
The $size您尝试使用的运算符仅适用于“数组”以返回存在的条目数。再说一次,它仅适用于与.aggregate()
method.
如果您想省略诸如 a 之类的字符space
在一个字符串中然后$split and $reduce with $concat可以应用:
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 } }
);