2016-08-25 79 views
1

由于mongodb中的每个集合在_id列上都有一个默认索引,因此我想将其用于我的场景,如下所示。使用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") 
    } 
} 
) 

(OR)

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

(OR)

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列上的一个或多个字段。

感谢,

斯里兰卡

回答

2

你可以试试下面的查询,在第一种情况: -

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

谢谢..这工作。 – javauser

+0

请参阅find的文档。很高兴帮助。 – Shrabanee

+0

当我运行.explain()查询时,它似乎没有使用_id字段上的索引。它已经进行了收集扫描并且没有使用索引。为什么会这样? – javauser