gpt4 book ai didi

mongodb - 使用MongoDB _id字段作为多个字段的复合字段

转载 作者:行者123 更新时间:2023-12-03 01:13:10 24 4
gpt4 key购买 nike

由于 mongodb 中的每个集合在 _id 列上都有一个默认索引,因此我想将它用于我的场景,如下所示。

我的收藏如下,

{
"_id":{
"timestamp" : ISODate("2016-08-24T23:22:20.201Z"),
"departmentname" : "sales",
"city":"NJ"
}

//Other fields in my collection
}

通过这个结构,我可以进行如下查询,

db.getCollection('test').find(
{
"_id" : {
"timestamp" : ISODate("2016-08-21T23:22:20.201Z"),
"departmentname" : "sales",
"city":"NJ"
}
}
)

但是,当我按 _id 列的一部分的一个或多个字段进行查询时,如下所示,

db.getCollection('test').find(
{
"_id" : {
"timestamp" : ISODate("2016-08-21T23:22:20.201Z")
}
}
)

(或)

db.getCollection('test').find(
{
"_id" : {
"departmentname" : "sales"
}
}
)

(或)

db.getCollection('test').find(
{
"_id" : {
"departmentname" : "sales",
"city":"NJ"
}
}
)

我没有看到任何返回的文件

当我检查 .explain() 时,我发现它使用了 Index 但没有找到任何文档。

此外,我想对时间戳字段进行日期范围查询,并对 _id 列中的一个或多个字段进行查询,如下所示,

db.getCollection('test').find(
{

"_id.timestamp" : {
"$gte": ISODate("2011-08-21T23:22:20.201Z")
},
"_id.departmentname" : "sales"
}
)

但是,我没有看到任何返回的文件。当我运行 .explain() 时,我看到它使用了 colscan 而不是索引。

有人可以帮助我以正确的方式通过 _id 列上的一个或多个字段进行查询吗?

谢谢

斯里兰卡

最佳答案

您可以尝试以下查询,第一种情况:-

db.getCollection('test').find(
{
"_id.timestamp" : ISODate("2016-08-21T23:22:20.201Z")
})

这适用于多个字段:

db.getCollection('test').find(
{
"_id.timestamp" : ISODate("2016-08-21T23:22:20.201Z"),
"_id.departmentname" : "sales",
})

关于mongodb - 使用MongoDB _id字段作为多个字段的复合字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140386/

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