根据子文档数组过滤mongodb中文档的多条件
我需要使用多个条件筛选所有文档根据子文档数组过滤mongodb中文档的多条件,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我需要使用多个条件筛选所有文档 { "name": "Maths", "excludeUserIds": [ { "_id": 33, "groupIds": [ "a", "b",
{
"name": "Maths",
"excludeUserIds": [
{
"_id": 33,
"groupIds": [
"a",
"b",
"c"
]
}
]
},
{
"name": "Science",
"excludeUserIds": [
{
"_id": 24,
"groupIds": [
"a",
"x",
"b"
]
}
]
},
{
"name": "Health",
"excludeUserIds": []
},
{
"name": "English",
"excludeUserIds": [
{
"_id": 33,
"groupIds": []
}
]
}
如果excludeUserId.\u id
不等于给定值和excludeUserId.groupId
不在给定数组中,则需要返回文档。
我写的mongo脚本是
{
"$match": {
"excludeUserIds": {
"$elemMatch": {
"_id": {
$ne: 33
},
"groupIds": {
$nin: [
"a"
]
}
}
}
}
}
我希望这将返回所有不带数学的文档。但是我没有像我期望的那样工作。显然我错过了什么。提前谢谢。我创造了一个
嵌套数组也需要使用$elemMatch
编辑:
您可以检查是否存在/是否为空也可以获取这些信息。尝试使用此选项
db.collection.find({
"excludeUserIds._id": { $ne: 33 },
"excludeUserIds.groupIds": { $nin: ["a"] }
})
这可能不是解决方案,但会给出所需的结果。如果要求返回除数学以外的所有科目,您的逻辑应该是
如果ExcludeUserId.\u id不等于给定值且或ExcludeUserId.GroupId不在给定数组中
可以转换为以下代码,将逻辑从转换为!A | | |!B
到等效的!(A和B)
用于较短的代码
db.collection.aggregate([
{
$match: {
excludeUserIds: {
$not: {
$elemMatch: {
_id: 33,
groupIds: { $all: ["a"] }
}
}
}
}
}
])
如果只需要将excludeUserIds.groupIds
与一个值(而不是数组)匹配,则可以执行以下操作
db.collection.aggregate([
{
$match: {
excludeUserIds: {
$not: {
$elemMatch: {
_id: 33,
groupIds: "a"
}
}
}
}
}
])
这是唯一的科学。在我的情况下,除了Maths@Nishakar您是否有机会检查我忘记通知的更新检查我的编辑并让我知道。您想将excludeUserIds.groupIds
与包含一个元素的数组相匹配,还是也可以是多个元素?非常感谢,你救了我一天,但你是怎么做到的?我需要同时满足这两个条件,@Nishakar我想你是糊涂了。如果你想要除数学以外的所有课程,只需要满足其中一个条件。如果必须满足这两个条件,则英语不会被包括在内,因为\u id
是33
,而科学不会被包括在内,因为它在groupid
中包含“a”
db.collection.aggregate([
{
$match: {
excludeUserIds: {
$not: {
$elemMatch: {
_id: 33,
groupIds: { $all: ["a"] }
}
}
}
}
}
])
db.collection.aggregate([
{
$match: {
excludeUserIds: {
$not: {
$elemMatch: {
_id: 33,
groupIds: "a"
}
}
}
}
}
])