gpt4 book ai didi

mongodb - 查找数组中没有项具有值的所有记录

转载 作者:行者123 更新时间:2023-12-02 09:35:42 25 4
gpt4 key购买 nike

我想查找数组中没有项目(things1 或 things2)具有“颜色”值的所有记录。(因此所有颜色要么为“”,要么为空,要么不存在)

这是数据结构 -

{
_id: objectId(),
things1: [
{
height:
weight:
color:
}
],
things2: [
{
size:
flavor:
color:
}
]
}

我已经尝试过这个:

.find({
$and: [
{
things1:{
$elemMatch: {
$or: [
{
color: ''
},
{
color: null
},
{
color: { $exists: false }
}
]
}
}
},
{
things2:{
$elemMatch: {
$or: [
{
color: ''
},
{
color: null
},
{
color: { $exists: false }
}
]
}
}
}
]
})

这会拉回任何项目具有空白、空或不存在“颜色”的任何记录...意思是如果“things1”中有三个东西,并且三者中的两个有颜色,第三个是空字符串,并且“things2”中的所有项目都有颜色 - 上面的查询将返回此文档

我只想要所有“颜色”字段均为空白、空或不存在的记录。

任何帮助表示赞赏谢谢

最佳答案

我们可以考虑一个反向路由,即必须为 null、不存在或为空的字符串基本上是一个没有字符的字符串。我们可以计算 ( 填充颜色的 NOR存在于 things1 数组中,填充颜色存在于 things2 数组中)。

例如:

db.collection.find({
$nor:[
{
"things1.color":/.+/
},
{
"things2.color":/.+/
}
]
}).pretty()

关于mongodb - 查找数组中没有项具有值的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com