我有一个查询需要写在需要确定数组中元素数量的位置(我知道可以通过 $project
和 $size
然后 $match
来完成),但是然后我需要能够处理满足这个条件的数组项,如果不满足条件,则留下它们。我不想通过 $match
排除不符合条件的项目
以下是对数组中无法满足我的需要的项目进行计数的标准方法:
db.collection.aggregate([
{ $project: { _id:1,
themeArraySize: { $gt: [ {$size: "$themes" }, 1 ] } } },
{ $match: { themeArraySize : true }} ,
])
我需要将其包装在一个条件中,并且不通过匹配排除任何内容
我想要为我的主题数组实现的“逻辑”是这样的:
- 如果数组的长度 > 1 并且
- 存在一个值为“[]”或“未选择主题”的数组项
- THEN 从主题数组中 $PULL“[]”或“NO THEMES SELECTED”
- 否则返回
themes
数组
我正在努力解决的部分是如何处理真正的逻辑
用一句话来说:
“如果数组中有一个主题是“[]”,并且这是唯一的主题,则保留它。但是如果存在“[]”,并且还有其他主题,则删除“[” ]' 来自数组”
我已经开始了:
{
"$project": {
"conversationid": 1,
"themes": {
"$cond": [
{
"$and": [
{
"$or": [
{
"$in": [
"[]",
"$themes"
]
},
{
"$in": [
"NO THEMES SELECTED",
"$themes"
]
}
]
},
{
"$themes": {
"$gte": [
******I WANT TO SAY THAT THE THEMES ARRAY MUST BE >1 IN SIZE HERE******
]
}
}
]
},
{
"$pull": {
"$themes": {
"$in": [
"NO THEMES SELECTED",
"[]"
]
}
}
},
"$themes"
]
}
}
},
但我感觉我想做的事情是不可能的
谢谢
最佳答案
您可以使用$addFields替换现有的 themes
字段,$cond定义你的逻辑和 $filter要从 themes
数组中删除某些特定项目,请尝试:
db.collection.aggregate([
{
$addFields: {
themes: {
$cond: [
{ $eq: [ { $size: "$themes"} , 1 ] },
"$themes",
{
$filter: {
input: "$themes",
cond: {
$and: [
{ $ne: [ "$$this", "[]" ] },
{ $ne: [ "$$this", "NO THEMES SELECTED" ] }
]
}
}
}
]
}
}
}
])
以下数据:
db.collection.save({ themes: [ "something" ] })
db.collection.save({ themes: [ "[]" ] })
db.collection.save({ themes: [ "NO THEMES SELECTED" ] })
db.collection.save({ themes: [ "Something else", "NO THEMES SELECTED" ] })
db.collection.save({ themes: [ "Something else (2)", "[]" ] })
返回:
{ "_id" : ObjectId("5c6d75246fb49f04a0a1f6a6"), "themes" : [ "something" ] }
{ "_id" : ObjectId("5c6d75246fb49f04a0a1f6a7"), "themes" : [ "[]" ] }
{ "_id" : ObjectId("5c6d75246fb49f04a0a1f6a8"), "themes" : [ "NO THEMES SELECTED" ] }
{ "_id" : ObjectId("5c6d75246fb49f04a0a1f6a9"), "themes" : [ "Something else" ] }
{ "_id" : ObjectId("5c6d75246fb49f04a0a1f6aa"), "themes" : [ "Something else (2)" ] }
关于mongodb - 不使用 $match 获取条件内数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788239/