簡體   English   中英

在MEAN堆棧中,如何做一次MongoDB索引?

[英]In a MEAN stack, how can I do one-time MongoDB indexing?

我正在將Mongoose與Node.js和MongoDB一起使用。 我正在以Node.js的形式連接到Mongoose,

db = mongoose.connect('mongodb://localhost/my_database_name')

如何在node.js中配置一次以創建集合索引

我的應用程序的目錄結構基於此教程

HTML        views/
Angular.js  public/javascript/
Express.js  routes/
Node.js     app.js
Mongoose js models/, set up in app.js
Mongo db    set up in app.js

指導我如何在Node.js的MongoDB集合上提供索引。

正如人們評論的那樣,最好的方法是在Mongoose模式中設置索引。 就我而言,它在models / Animal.js文件中。

對於單索引,您可以定義何時定義架構

var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true }
});

有關更多信息,請參閱文檔

對於復合索引 ,您可以在Schema定義之后的同一文件中添加一行,如下所示:

animalSchema.index({"tags": 1, "name": 1});

排序順序為升序(1)或降序(-1)。

順便說一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1)來獲取第一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM