[英]$in Query on Array Field Mongo db
I have a doc like this我有一个这样的文档
{
"_id" : "oidfi",
"users": [
{
"_id": "q",
"tags": ["a", "b", "c"],
"age": 20
},
{
"_id": "q",
"tags": ["x", "y", "z"],
"age": 30
}
],
"type": "repo"
}
I want to filter the users array with several fields ( I'm able to do that with the below query )我想用几个字段过滤用户数组(我可以用下面的查询来做到这一点)
{
"$match": {
"$and": [
{
"_id": "a506f8af6f510f616bea14715276d474d2b363f0aef10443cc0f11559b139147"
}
]
}
},
{
"$project": {
"users": {
"$filter": {
"input": "$users",
"as": "users",
"cond": {
"$and": [
{
"$gte": [
"$$user.age",
15
]
}
]
}
}
}
}
}
]
is there a way for me to add condition where I give a list of tags items and get the users who are matching at least one item from their tags array有没有办法让我添加条件,我给出一个标签项目列表,并从他们的标签数组中获取至少匹配一个项目的用户
$$user.tags.containsAny(["a", "x"])
Thanks谢谢
You can do the followings in an aggregation pipeline:您可以在聚合管道中执行以下操作:
$setIntersection
to find out the intersection of the users.tags
array and your input array ie ["a", "x"] in your example $setIntersection
找出users.tags
数组和您的输入数组的交集,即 ["a", "x"] 在您的示例中$size
to find the size of array in step 1 $size
在步骤 1 中查找数组的大小$match
by the size of step 2 larger than 0 $match
步 2 的大小大于 0"anyTagsMatched": {
$gt: [
{
$size: {
"$setIntersection": [
"$users.tags",
[
"a",
"x"
]
]
}
},
0
]
}
Here is the Mongo playground for your reference.这是Mongo 游乐场供您参考。
You may have like following你可能喜欢以下
db.collection.aggregate([
{
"$project": {
"users": {
"$filter": {
"input": "$users",
"cond": {
"$and": [
{ "$gte": [ "$$this.age", 15 ] },
{
$gt: [
{
$size: {
"$setIntersection": [
"$$this.tags",
[ "a", "x" ]
]
}
},
0
]
}
]
}
}
}
}
}
])
Working Mongo playground工作Mongo 游乐场
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.