如何查询 AWS DocumentDB (DocDB) 以使用 $where 比较两个字段
How to query AWS DocumentDB (DocDB) to compare two fields using $where
AWS 的 DocumentDB 与 Mongo 不同——具体来说,您不能在查找查询中使用 $where
运算符。具体来说,我希望进行一个查询,以显示文档字段 x
== y
的所有结果,例如:
> db.my_collection.find({$where:"this.x==this.y"}).pretty();
Error: error: {
"ok" : 0,
"operationTime" : Timestamp(1623784861, 1),
"code" : 303,
"errmsg" : "Feature not supported: $where"
}
这在 DocDB 中是如何完成的?
以下是一种可能的解决方法,可以使结果接近您在 DocumentDB 中的预期结果。它类似于没有 WHERE
的 SQL 自连接。
如果您希望 joined 元素与 MongoDB 中显示的完全一样,则需要提取它。请注意,与 $where
运算符相比,在大量数据中使用聚合可能会对性能产生影响。一如既往,请在部署到生产环境之前进行测试。
以下是用于在 DocumentDB 中测试查询的步骤
- 示例数据
db.tableA.insert( { "id":"123", "key1":"fjf", "key2":[{},{}] } )
db.tableA.insert( { "id":"123", "key1":"xyz", "key2":[{"x": "1"},{"y": "1"}], "key3": "123" } )
db.tableA.insert( { "id":"456", "key1":"abc", "key3": "456" } )
- 查询
db.tableA.aggregate([
{
$lookup:
{
from: "tableA",
localField: "id",
foreignField: "key3",
as: "joined"
}
},
{ $unwind :"$joined" },
{ $redact: { $cond: [ { $eq: [ "$key3", "$joined.key3" ] }, "$$KEEP", "$$PRUNE" ] } }
{ $project: { joined: 1, _id: 0 } }
]).pretty()
AWS 的 DocumentDB 与 Mongo 不同——具体来说,您不能在查找查询中使用 $where
运算符。具体来说,我希望进行一个查询,以显示文档字段 x
== y
的所有结果,例如:
> db.my_collection.find({$where:"this.x==this.y"}).pretty();
Error: error: {
"ok" : 0,
"operationTime" : Timestamp(1623784861, 1),
"code" : 303,
"errmsg" : "Feature not supported: $where"
}
这在 DocDB 中是如何完成的?
以下是一种可能的解决方法,可以使结果接近您在 DocumentDB 中的预期结果。它类似于没有 WHERE
的 SQL 自连接。
如果您希望 joined 元素与 MongoDB 中显示的完全一样,则需要提取它。请注意,与 $where
运算符相比,在大量数据中使用聚合可能会对性能产生影响。一如既往,请在部署到生产环境之前进行测试。
以下是用于在 DocumentDB 中测试查询的步骤
- 示例数据
db.tableA.insert( { "id":"123", "key1":"fjf", "key2":[{},{}] } ) db.tableA.insert( { "id":"123", "key1":"xyz", "key2":[{"x": "1"},{"y": "1"}], "key3": "123" } ) db.tableA.insert( { "id":"456", "key1":"abc", "key3": "456" } )
- 查询
db.tableA.aggregate([ { $lookup: { from: "tableA", localField: "id", foreignField: "key3", as: "joined" } }, { $unwind :"$joined" }, { $redact: { $cond: [ { $eq: [ "$key3", "$joined.key3" ] }, "$$KEEP", "$$PRUNE" ] } } { $project: { joined: 1, _id: 0 } } ]).pretty()