简体   繁体   中英

MongoDb Indexing the ObjectId(_id) for the arrays of objects

I have an mongodb collection such as products example.

{  
    "_id" : ObjectId("5ec5229bda162e089d2ab4ff"),  
    "name" : "Fruit",
    "price" : 2.0,
    "manufacture": [   
        {_id:  ObjectId("5ec5229bda162e089d2ab4ff"), m_name: "M-1" },   
        {_id:  ObjectId("5ec5229bda162e089d2ab4ff"), m_name: "M-2" } 
    ]
}

I need to index the manufacture._id field since I am querying on this field for several times in my application.

Can I index them or it will be automatically indexed since it also has _id in it?.

According to MongoDB documentation : 'MongoDB creates a unique index on the _id field during the creation of a collection.'

So no, your array index will not be created automatically.

To create the index you can specify it in the schema. Something like this (not tested):

_id: {
  type: ObjectId,
  required: true,
  index: true,
  unique:true
}

Or also:

YourSchema.index({ "manufacture._id": 1 }, { unique: true });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM