【问题标题】:Use MongoDB _id field as composite field with multiple fields使用 MongoDB _id 字段作为具有多个字段的复合字段
【发布时间】:2016-08-25 08:34:15
【问题描述】:

由于 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() 检查时,我发现它使用了索引,但没有找到任何文档。

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

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

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

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

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

谢谢,

斯里

【问题讨论】:

    标签: mongodb spring-data-mongodb bson


    【解决方案1】:

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

    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", 
    })
    

    【讨论】:

    • 请参考 find 的文档。很高兴它有帮助。
    • 当我使用查询运行 .explain() 时,似乎 _id 字段上的索引尚未使用。它进行了集合扫描并且未使用索引。为什么会这样?
    • @javauser 请参阅docs.mongodb.com/manual/core/index-single/…,了解有关索引嵌入文档时 MongoDB 行为的重要信息。基本上,“字段顺序很重要,嵌入的文档必须完全匹配。”我认为创建复合索引会更适合您的用例。
    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多