索引:

 

db.media.createIndex({"Tracklist": 1})

  • 1表示升序
  • -1表示降序

 

我们要着重看一下对数组创建索引的情况。

构建一个集合:db.media.insertOne({"Type": "CD", "Artist": "Nirvana", "Title": "Nevermind", "Tracklist": [{"Track": 1, "Title": "AAA", "Length": 10},{"Track": 2, "Title": "BBB", "Length": 20}]})

MongoDB 学习笔记之 索引

 

对数组创建索引:

db.media.createIndex({"Tracklist": 1})

MongoDB 学习笔记之 索引

查询:

db.media.find({"Tracklist.Track": 2}).explain(true)

MongoDB 学习笔记之 索引

发现并未使用索引。

db.media.find({"Tracklist": {"Title": "AAA"}}).explain(true)

MongoDB 学习笔记之 索引

 db.media.find({"Tracklist": {"Track": 1, "Title": "AAA", "Length": 10}}).explain(true)

MongoDB 学习笔记之 索引

都使用了Tracklist索引。

所以如果对数组建立了索引,查询要指定的是文档对象,而不是键值。

相关文章:

  • 2021-12-15
  • 2021-08-29
  • 2022-02-14
  • 2021-11-05
  • 2022-02-24
  • 2021-05-31
  • 2021-09-24
猜你喜欢
  • 2021-11-06
  • 2022-01-28
  • 2021-11-16
  • 2021-12-03
相关资源
相似解决方案