以下是我的收藏“fullclicklogs”,其中包含许多json文档:
{
"_id" : ObjectId("58fe78dcfbe21fa7896552e8"),
"preview" : false,
"offset" : 0,
"result" : {
"tab_name" : "People-Tab",
"page_name" : "PEOPLE",
"result_number" : "1",
"page_num" : "0",
}
}
{
"_id" : ObjectId("58fe78dcfbe21fa7896552e9"),
"preview" : false,
"offset" : 0,
"result" : {
"tab_name" : "People-Tab",
"page_name" : "PEOPLE",
"result_number" : "5",
"page_num" : "0",
}
}
我想在我的新收藏集“doc_rank”中添加一个新字段“DOCRANK”DOCRANK = page_num*25+result_number
更新:由于page_num和result_number是字符串,我使用以下命令将它们转换为int:
>db.fullclicklogs.find().forEach( function (x) {
x.result.page_num = parseInt(x.result.page_num);
db.fullclicklogs.save(x);
});
>db.fullclicklogs.find().forEach( function (x) {
x.result.result_number = parseInt(x.result.result_number);
db.fullclicklogs.save(x);
});
错误:
2017-04-25T11:50:54.830-0700 E QUERY [thread1] TypeError: x.result is undefined :
@(shell):2:1
DBQuery.prototype.forEach@src/mongo/shell/query.js:501:1
@(shell):1:1
>
下面是我用来获取DOCRANK的聚合,但我的结果集合中仍然获得值null:
db.getCollection('fullclicklogs').aggregate( [
{
$project: {
DOCRANK: {
$let: {
vars: {
total: { $multiply: [ "$result.page_num", 25 ] },
},
in: { $add: [ "$$total", "$result.result_number" ] }
}
}
}
},
{
$out: "doc_rank1"
}
] )
更新:使用点表示法来修复我的代码。但现在我得到“$ multiply只支持数字类型,而不是字符串”
汇总输出:
assert: command failed: {
"ok" : 0,
"errmsg" : "$multiply only supports numeric types, not string",
"code" : 16555,
"codeName" : "Location16555"
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:16:14
assert.commandWorked@src/mongo/shell/assert.js:370:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5
@(shell):1:1
2017-04-25T11:12:11.420-0700 E QUERY [thread1] Error: command failed: {
"ok" : 0,
"errmsg" : "$multiply only supports numeric types, not string",
"code" : 16555,
"codeName" : "Location16555"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:16:14
assert.commandWorked@src/mongo/shell/assert.js:370:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1319:5
@(shell):1:1
我可以知道我的代码有什么问题吗?任何帮助表示赞赏。感谢
答案 0 :(得分:1)
您需要使用点表示法来访问嵌入字段。 result
是嵌入式文档,result_number
和page_num
是嵌入式字段。
尝试
db.getCollection('fullclicklogs').aggregate( [
{
$project: {
DOCRANK: {
$let: {
vars: {
total: { $multiply: [ "$result.page_num", 25 ] },
},
in: { $add: [ "$$total", "$result.result_number" ] }
}
}
}
},
{
$out: "doc_rank1"
}
] )
更多https://docs.mongodb.com/manual/core/document/#document-dot-notation