forked from mongodb/docs-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-code-examples.rb
112 lines (93 loc) · 2.44 KB
/
index-code-examples.rb
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
require 'mongo'
# Replace the placeholders with your credentials
uri = "<connection string>"
# Sets the server_api field of the options object to Stable API version 1
options = { server_api: { version: "1" }}
# Creates a new client and connect to the server
client = Mongo::Client.new(uri, options)
database = client.use('<database name>')
collection = database[:<collection name>]
# Single Field
# start-index-single
collection.indexes.create_one({ <field name>: 1 })
# end-index-single
# Compound
# start-index-compound
collection.indexes.create_one({ <field name 1>: -1, <field name 2>: 1 })
# end-index-compound
# Multikey
# start-index-multikey
collection.indexes.create_one({ <field name>: 1 })
# end-index-multikey
# Geospatial
# start-index-geospatial
collection.indexes.create_one({ <GeoJSON field name>: '2dsphere' })
# end-index-geospatial
# Atlas Search
# Create Search Index
# start-create-search-index
index_definition = {
name: '<index name>',
definition: {
mappings: {
dynamic: false,
fields: { <field name>: {type: '<field type>'} }
}
}
}
collection.database.command(
createSearchIndexes: '<collection name>',
indexes: [index_definition]
)
# end-create-search-index
# List Search Indexes
# start-list-search-indexes
collection.database.command(listSearchIndexes: '<collection name>')
# end-list-search-indexes
# Update Search Indexes
#start-update-search-indexes
updated_definition = {
mappings: {
dynamic: false,
fields: { <updated field name>: { type: '<field type>' } }
}
}
collection.database.command(
updateSearchIndex: '<collection name>',
name: '<index name>',
definition: updated_definition
)
#end-update-search-indexes
# Delete Search Index
# start-drop-search-index
collection.database.command(
dropSearchIndex: '<collection name>',
name: '<index name>'
)
# end-drop-search-index
# Text Index
# start-text
collection.indexes.create_one( { :<field name> => 'text' } )
# end-text
# Create Many
# start-index-create-many
collection.indexes.create_many([
{ key: { <field name 1>: 1 } },
{ key: { <field name 2>: -1 } },
])
# end-index-create-many
# Delete an Index
# start-drop-single-index
collection.indexes.drop_one( '<index name>' )
# end-drop-single-index
# Drops all indexes in the collection.
# start-drop-all-index
collection.indexes.drop_all
# end-drop-all-index
# List an Index
# start-list-indexes
all_indexes.each do |index|
puts index
end
# end-list-indexes
client.close