gpt4 book ai didi

mongodb - 检索具有包含另一个文档属性的数组的文档

转载 作者:可可西里 更新时间:2023-11-01 09:37:12 25 4
gpt4 key购买 nike

我在 Mongo 中存储某种文件系统,其中目录被命名为类别。

类别 JSON 如下所示:

{
"name":"CategoryChildLevel2",
"parentId":"2",
"otherAttribute":"anyVal",
"breadcrumb":[
{
"name":"RootCategory",
"id":"1"
},
{
"name":"CategoryChildLevel1",
"id":"2"
}
]
}

FS 类别与 parentId 属性链接在一起。

我需要显示类别面包屑。通过用户导航,我们可以知道我们在 FS 上的位置,但是类别可以直接通过它们的 ID 访问(书签类别,搜索引擎......),而不需要任何 FS 导航。为了避免对数据库的递归调用,为了能够获取面包屑,我对其进行了非规范化。


问题是这个面包屑很难保持最新,因为顶级类别可以移动,因此它的所有子面包屑都必须更新。可以有很多子类别要更新,并且有不同的方法来处理这个问题。其中一些安全但代价高昂(递归),而另一些速度更快但可能导致一些不一致。


我想知道的是,是否可以进行查询以检索面包屑导航不佳的类别。我需要一个允许执行的查询:

Retrieve all the categories that do not have: last array element breadcrumb.id = parentId

我不认为“最后一个数组元素”部分是可能的,但能够做到也很好:

Retrieve all the categories that do not have: breadcrumb.id contains parentId

在 Scala 或 Java 驱动程序中可用的任何解决方案?我正在使用 Salat/Casbah。

这个问题可以帮助您了解我所面临的问题:Which DB would you use? MongoDB/Neo4j/SQL... all of them?

最佳答案

您可以使用 $where 执行检索所有不具有的类别:last array element breadcrumb.id = parentId 查询运算符(operator):

db.test.find({
// Find docs were breadcrumb is empty or its last element's id != parentId
$where: '!this.breadcrumb.length || this.breadcrumb[this.breadcrumb.length-1].id !== this.parentId'
})

关于mongodb - 检索具有包含另一个文档属性的数组的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068030/

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