在 Mongoose/MongoDB 中创建多字段索引

我试图找到文档,但是没有用,关于如何在 Mongoosejs 创建多字段索引。特别是我有两个字段需要被索引和唯一。将两个字段索引在一起的猫鼬模式示例是什么?

90868 次浏览

You call the index method on your Schema object to do that as shown here. For your case it would be something like:

mySchema.index({field1: 1, field2: 1}, {unique: true});

Defining indexes at the schema level is necessary when creating compound indexes.

animalSchema.index({ name: 1, type: -1 });

Reference: http://mongoosejs.com/docs/guide.html#indexes

    Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..


}
}

I have tested with sample data it is perfectly working as expected.

By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300 you should wrap the field names in single quotes, ie:

mySchema.index({'field1': 1, 'field2': 1}, {unique: true});

Happy Day!

import { Schema, Document, model } from 'mongoose';


import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';


export interface IUserMoodLocation extends Document {
userId?: IUser['_id'];
moodId?: IMood['_id'];
locationId?: ILocation['_id'];
}


const UserMoodLocationSchema: Schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
moodId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Mood'
},
locationId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Location'
}
});


UserMoodLocationSchema.index(
{ userId: 1, moodId: 1, locationId: 1 },
{ unique: true }
);


export const UserMoodLocation = model<IUserMoodLocation>(
'UserMoodLocation',
UserMoodLocationSchema
);