CosmosDB $elemMatch 语法错误
CosmosDB $elemMatch syntax error
对于 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
]
}
}
}
}
}
])
检查一下here
对于 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
]
}
}
}
}
}
])
检查一下here