azure-cosmosdb - CosmosDB $elemMatch 语法错误
问题描述
对于 CosmosDB 的 MongoDB API 中的某些命令,我收到一个奇怪的语法错误。假设我有一个名为“Collection”的集合,其中包含两个文档:
{
"_id" : 1,
"arr" : [
{
"_id" : 11
},
{
"_id" : 12
}
]
}
{
"_id" : 2,
"arr" : [
{
"_id" : 21
},
{
"_id" : 22
}
]
}
如果我尝试运行查询
db.getCollection('Collection').find( { _id : 2 }, { arr : { $elemMatch : { _id : 21 } } })
我得到结果
{
"_t" : "OKMongoResponse",
"ok" : 0,
"code" : 9,
"errmsg" : "Syntax error, incorrect syntax near '10'.",
"$err" : "Syntax error, incorrect syntax near '10'."
}
但是该命令在我本地托管的 MongoDB 实例上运行良好,返回了预期的结果:
{
"_id" : 2,
"arr" : [
{
"_id" : 21
}
]
}
无论如何,这肯定不是语法错误,但没有任何有用的错误信息。如果 CosmosDB 尚不支持这一点,有没有办法只获取存储在数组中的某些嵌入式文档?
如果我尝试使用聚合管道仅提取数组中的文档(我意识到这应该给出与上面的命令不同的结果,但它也适用于我的目的),如下所示:
db.getCollection('Collection').aggregate([{ "$unwind" : "$arr" }, { "$match" : { "arr._id" : 21 } }] )
我得到结果
{
"_t" : "OKMongoResponse",
"ok" : 0,
"code" : 118,
"errmsg" : "$match is currently only supported when it is the first and only stage of the aggregation pipeline. Please restructure your query to combine multiple $match stages into a single $match stage.",
"$err" : "$match is currently only supported when it is the first and only stage of the aggregation pipeline. Please restructure your query to combine multiple $match stages into a single $match stage."
}
所以这对我也不起作用。
解决方案
试试这个
db.collection.aggregate([
{
$match: {
"_id": 2
}
},
{
$project: {
arr: {
$filter: {
input: "$arr",
as: "ar",
cond: {
$eq: [
"$$ar._id",
21
]
}
}
}
}
}
])
在这里检查
推荐阅读
- javascript - bootstrap-datetimepicker-widget 未在弹出窗口中加载
- extjs - 当我的用户在上海并使用 Win8.1 和 IE11.x 操作一个应用程序页面时,我无法加载该页面
- amazon-web-services - 如何使用 golang 检查 s3 对象大小
- php - 如何将我的 html 导出为 pdf 并下载?
- python - 如何在 Windows 上使用 Python 创建 tar.gz 时设置执行权限
- php - 无法在 prestashop Context::getContext()->cookie 中找到 cookie 值,但它显示在 $_COOKIE 中?
- progressive-web-apps - Pwa venia 主题产品页面滑块不起作用
- java - kotlin:检查一个类是否是对象类?
- android - 将我的屏幕内容远程显示到其他设备
- swift - 按下 tableviewCell 中的按钮并执行另一个控制器