鉴于收集的“示例”:
{_id: 1, prediction: "H", result: "A"}
{_id: 2, prediction: "H", result: "H"}
{_id: 3, prediction: "A", result: "A"}我需要做什么才能找到预测值和结果值匹配的记录?即。2号和3号文件?
找到所有的"H“预测是:
db.example.find( { prediction: "H" } )但是,我需要用相同文档的结果字段中的值替换文字"H“。
编辑:对不起,我应该说我在使用Mongo 3.6。
发布于 2018-02-28 09:36:20
你可以使用加法。
db.example.aggregate(
[
{
$project:
{
_id: 1,
prediction: 1,
result: 1,
compare: { $eq: [ "$prediction", "$result" ] }
}
},
{
$match:
{
compare: true
}
}
]
)发布于 2018-02-28 09:37:38
您应该能够使用聚合查询来完成这一任务,请尝试$redact阶段:
db.test.aggregate(
[
{ $redact: {
$cond: {
if: { $eq: [ "$prediction", "$result" ] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
);这将产生以下结果:
{ "_id" : 2, "prediction" : "H", "result" : "H" }
{ "_id" : 3, "prediction" : "A", "result" : "A" }有关redact的更多信息可以在这里找到- https://docs.mongodb.com/manual/reference/operator/aggregation/redact/#redact-aggregation
发布于 2018-02-28 09:50:25
如果您正在使用3.6,这将有效。请参阅此
db.getCollection('TEST').find( { $where: function() {
return this.prediction == this.result
} })结果:
{
"_id" : 2,
"prediction" : "H",
"result" : "H"
}
{
"_id" : 3,
"prediction" : "A",
"result" : "A"
}https://stackoverflow.com/questions/49026048
复制相似问题