/
get-indexes.js
72 lines (56 loc) · 2.02 KB
/
get-indexes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// db.collection.getIndexes() method example in NodeJS
import { MongoClient } from "mongodb";
async function main() {
// Define MongoDB connection URI
const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";
// Create a client
const mongo = new MongoClient(uri);
try {
await mongo.connect();
const database = mongo.db("bigboxcode");
const customerCollection = database.collection("customer");
// Create unique index on email field
let commandResult = await customerCollection.createIndex(
{ email: 1 },
{ unique: true }
);
console.log(
"Command: db.customer.createIndex({email: 1}, {unique: true}) | Result:",
commandResult
);
// Set index with name
commandResult = await customerCollection.createIndex(
{ name: 1 },
{ name: "my_name_idx" }
);
console.log(
'Command: db.customer.createIndex({name: 1}, {name: "my_name_idx"}) | Result: ',
commandResult
);
// Set compound index on address fields with hashed zipcode
commandResult = await customerCollection.createIndex(
{ "address.country": 1, "address.state": 1, "address.zipcode": "hashed" },
{ name: "address.country_1_address.state_1_address.zipcode_hashed" }
);
console.log(
'Command: Command: db.customer.createIndex({"address.country": 1, "address.state" : 1, "address.zipcode" : "hashed"}) | Result: ',
commandResult
);
// Set hidden index
commandResult = await customerCollection.createIndex(
{ profileCompletenessScore: 1 },
{ hidde: true }
);
console.log(
"Command: db.customer.createIndex({profileCompletenessScore: 1}, {hidden: true}) | Result: ",
commandResult
);
// Check indexes
commandResult = await customerCollection.indexes();
console.log("Command: db.customer.getIndexes() | Result:", commandResult);
} finally {
await mongo.close();
}
}
await main().catch(console.error);
process.exit(0);