How do I create a unique index for exactly one field in Mongo shell, while inserting multiple fields for each of my objects at once?

17 views Asked by At

I'm currently using the MongoDB shell v5.0.10 to set up a database for further use and was wondering if it is possible to combine the following commands into one command (and how):

 db.customers.insertMany([
     {"customer": "Bosch", "city": "Stuttgart",  "AccNo": 70174, "orders": 1088},
     {"customer": "ZDF",   "city": "Mainz",      "AccNo": 55116, "orders": 40530},
     {"customer": "EF",    "city": "Düsseldorf", "AccNo": 40479, "orders": 178650}
 ])

including:

db.customers.createIndex({"AccNo": 40479}, {unique: true})

Ideally, I'd have a one line command like:

db.customers.insertMany([
    {"customer": "Bosch", "city": "Stuttgart",  "AccNo": 70174 {unique: true}, "orders": 1088},
    {"customer": "ZDF",   "city": "Mainz",      "AccNo": 55116 {unique: true}, "orders": 40530},
    {"customer": "EF",    "city": "Düsseldorf", "AccNo": 40479 {unique: true}, "orders": 178650}
])

.. doing all that at once.

If not obvious:

I'm trying to have the "AccNo" as a unique index, while also assigning & creating all the other stated fields & values above - so I don't have to create an _id, neither using the automatically created cryptic ObjectId for calling Objects later on.

Thank you in advance!

0

There are 0 answers