MongoDB:对输入文档变量使用匹配 [英] MongoDB: Using match with input document variables
问题描述
为什么我必须使用以下代码:{ $match: { $expr: { <aggregation expression> } } }
使用文档输入变量来匹配文档,而不是使用{ $match: { <query> } }
?
Why do I have to use this code: { $match: { $expr: { <aggregation expression> } } }
to match a document using a document input variable as opposed to doing: { $match: { <query> } }
?
例如:
$lookup: {
from: "comments",
let: { myvar: '$myInputDocVariable'},
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$varFromCommentDocument", "$$myvar" ] },
]
}
}
},
],
as: "returnedValue"
}
上面的查询工作正常,但下面的查询无法正常工作.为什么是这样?这是否意味着如果在$lookup
管道中使用输入变量,就必须使用$expr
?为什么呢?
The query above works fine but the query below does not work as expected. Why is this? Does this mean that if you are using input variables in a $lookup
pipeline you have to use $expr
? why is that?
$lookup: {
from: "comments",
let: { myvar: '$myInputDocVariable'},
pipeline: [
{ $match: { "$varFromCommentDocument", "$$myvar" } }
],
as: "returnedValue"
}
推荐答案
这是否意味着如果您在$ lookup中使用输入变量 管道,您必须使用$ expr
Does this mean that if you are using input variables in a $lookup pipeline you have to use $expr
是正确的,默认情况下在过滤器中,即;在.find()
的筛选器部分或$match
聚合阶段,您不能使用文档中的现有字段.
Yes correct, by default in filters i.e; in filter part of .find()
or in $match
aggregation stage you can't use an existing field in the document.
如果根本需要在查询过滤器中使用现有字段的值,则需要使用聚合管道,因此,为了在.find()
或$match
中使用聚合管道,您需要将过滤器查询包装为 $ expr .使用$expr
包装使用访问通过$match
中的$lookup
过滤器的let
创建的局部变量的相同方法.
If at all if you need to use existing field's value in your query filter then you need to use aggregation pipeline, So in order to use aggregation pipeline in .find()
or in $match
you need to wrap your filter query with $expr. Same way to access local variables got created using let
of $lookup
filter in $match
needs to be wrapped by $expr
.
让我们考虑以下示例:
示例文档:
[
{
"key": 1,
"value": 2
},
{
"key": 2,
"value": 4
},
{
"key": 5,
"value": 5
}
]
查询:
db.collection.find({ key: { $gt: 1 }, value: { $gt: 4 } })
Or
db.collection.aggregate([ { $match: { key: { $gt: 1 }, value: { $gt: 4 } } } ])
测试: mongoplayground
如果您看到上述查询,请同时输入1
& 4
传递给查询,但是您在下面的查询中尝试尝试匹配key
字段== value
字段-它不起作用:
If you see the above query both input 1
& 4
are passed into query but it you check below query where you try to match key
field == value
field - it doesn't work :
db.collection.aggregate([ { $match: { key: { $eq: "$value" } } } ])
测试: mongoplayground
在比较两个现有字段之前,您不能这样做,因为这意味着您正在检查具有key
字段值作为字符串"$value"
的文档.因此,要说它不是字符串,实际上是对value
字段的引用,您需要使用 $ eq 聚合运算符,而不是
Above as you're comparing two existing fields then you can't do that as it mean you're checking for docs with key
field value as string "$value"
. So to say it's not a string it's actually a reference to value
field you need to use $eq aggregation operator rather than $eq query operator like below :
db.collection.aggregate([ { $match: { $expr: { $eq: [ "$key", "$value" ] } } } ])
测试: mongoplayground
这篇关于MongoDB:对输入文档变量使用匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!