userver: userver/storages/mongo/options.hpp Source File
Loading...
Searching...
No Matches
options.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/mongo/options.hpp
4/// @brief Query options
5
6#include <chrono>
7#include <cstddef>
8#include <cstdint>
9#include <initializer_list>
10#include <optional>
11#include <string>
12#include <string_view>
13#include <utility>
14#include <vector>
15
16#include <userver/formats/bson/bson_builder.hpp>
17#include <userver/formats/bson/document.hpp>
18#include <userver/formats/bson/value.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22/// Collection operation options
23namespace storages::mongo::options {
24
25/// @brief Read preference
26/// @see https://docs.mongodb.com/manual/reference/read-preference/
28 public:
29 enum Mode {
30 /// read from primary, default mode
32 /// read from secondary
34 /// read from primary if available, fallback to secondary
36 /// read from secondary if available, fallback to primary
38 /// read from any host with the lowest latency
40 };
41
42 explicit ReadPreference(Mode mode);
43 ReadPreference(Mode mode, std::vector<formats::bson::Document> tags);
44
45 Mode GetMode() const;
46 std::optional<std::chrono::seconds> GetMaxStaleness() const;
47 const std::vector<formats::bson::Document>& GetTags() const;
48
49 /// @brief Sets maximum replication lag for eligible replica.
50 /// @note Must be at least 90 seconds, cannot be used with kPrimary mode.
52 std::optional<std::chrono::seconds> max_staleness);
53
54 /// @brief Adds a tag to the tag set.
55 /// @note Cannot be used with kPrimary mode.
57
58 private:
59 Mode mode_;
60 std::optional<std::chrono::seconds> max_staleness_;
61 std::vector<formats::bson::Document> tags_;
62};
63
64/// @brief Read concern
65/// @see https://docs.mongodb.org/manual/reference/readConcern/
66enum class ReadConcern {
67 /// no replication checks, default level
68 kLocal,
69 /// return data replicated to a majority of RS members
71 /// waits for all running majority writes to finish before read
73 /// no replication checks, may return orphaned documents if sharded; since 3.6
75};
76
77/// @brief Write concern
78/// @see https://docs.mongodb.org/manual/reference/write-concern/
80 public:
81 enum Level {
82 /// Wait until propagation to a "majority" of RS nodes
84 /// Do not check for operation errors, do not wait for write, same as `0`
86 };
87
88 /// Default timeout for "majority" write concern
90
91 /// Creates a write concern with the special level
92 explicit WriteConcern(Level level);
93
94 /// Creates a write concern waiting for propagation to `nodes_count` RS nodes
95 explicit WriteConcern(size_t nodes_count);
96
97 /// Creates a write concern defined in RS config
98 explicit WriteConcern(std::string tag);
99
100 bool IsMajority() const;
101 size_t NodesCount() const;
102 const std::string& Tag() const;
103 std::optional<bool> Journal() const;
104 const std::chrono::milliseconds& Timeout() const;
105
106 /// Sets write concern timeout, `0` means no timeout
107 WriteConcern& SetTimeout(std::chrono::milliseconds timeout);
108
109 /// Sets whether to wait for on-disk journal commit
111
112 private:
113 size_t nodes_count_;
114 bool is_majority_;
115 std::optional<bool> journal_;
116 std::string tag_;
117 std::chrono::milliseconds timeout_;
118};
119
120/// Disables ordering on bulk operations causing them to continue after an error
121class Unordered {};
122
123/// Enables insertion of a new document when update selector matches nothing
124class Upsert {};
125
126/// Enables automatic one-time retry of duplicate key errors
128
129/// Specifies that FindAndModify should return the new version of an object
130class ReturnNew {};
131
132/// Specifies the number of documents to skip
133class Skip {
134 public:
135 explicit Skip(size_t value) : value_(value) {}
136
137 size_t Value() const { return value_; }
138
139 size_t value_;
140};
141
142/// @brief Specifies the number of documents to request from the server
143/// @note The value of `0` means "no limit".
144class Limit {
145 public:
146 explicit Limit(size_t value) : value_(value) {}
147
148 size_t Value() const { return value_; }
149
150 private:
151 size_t value_;
152};
153
154/// @brief Selects fields to be returned
155/// @note `_id` field is always included by default, order might be significant
156/// @see
157/// https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/
159 public:
160 /// Creates a default projection including all fields
161 Projection() = default;
162
163 /// Creates a projection including only specified fields
164 Projection(std::initializer_list<std::string_view> fields_to_include);
165
166 /// Includes a field into the projection
167 Projection& Include(std::string_view field);
168
169 /// @brief Excludes a field from the projection
170 /// @warning Projection cannot have a mix of inclusion and exclusion.
171 /// Only the `_id` field can always be excluded.
172 Projection& Exclude(std::string_view field);
173
174 /// @brief Setups an array slice in the projection
175 /// @param field name of the array field to slice
176 /// @param limit the number of items to return
177 /// @param skip the following number of items
178 /// @note `skip` can be negative, this corresponds to counting from the end
179 /// backwards.
180 /// @note `limit < 0, skip == 0` is equivalent to `limit' = -limit, skip' =
181 /// limit`.
182 /// @warning Cannot be applied to views.
183 Projection& Slice(std::string_view field, int32_t limit, int32_t skip = 0);
184
185 /// @brief Matches the first element of an array satisfying a predicate
186 /// @param field name of the array to search
187 /// @param pred predicate to apply to elements
188 /// @note Array field will be absent from the result if no elements match.
189 /// @note Empty document as a predicate will only match empty documents.
190 Projection& ElemMatch(std::string_view field,
191 const formats::bson::Document& pred);
192
193 /// @cond
194 /// Projection specification BSON access
195 const bson_t* GetProjectionBson() const;
196 /// @endcond
197
198 private:
199 formats::bson::impl::BsonBuilder projection_builder_;
200};
201
202/// Sorts the results
203class Sort {
204 public:
205 enum Direction {
206 kAscending,
207 kDescending,
208 };
209
210 /// Creates an empty ordering specification
211 Sort() = default;
212
213 /// Stores the specified ordering specification
215
216 /// Appends a field to the ordering specification
217 Sort& By(std::string_view field, Direction direction);
218
219 /// @cond
220 /// Sort specification BSON access
221 const bson_t* GetSortBson() const;
222 /// @endcond
223
224 private:
225 formats::bson::impl::BsonBuilder sort_builder_;
226};
227
228/// @brief Specifies an index to use for the query
229/// @warning Only plans using the index will be considered.
230class Hint {
231 public:
232 /// Specifies an index by name
233 explicit Hint(std::string index_name);
234
235 /// Specifies an index by fields covered
236 explicit Hint(formats::bson::Document index_spec);
237
238 /// @cond
239 /// Retrieves a hint value
240 const formats::bson::Value& Value() const;
241 /// @endcond
242
243 private:
244 formats::bson::Value value_;
245};
246
247/// @brief Specifies an array of filter documents that
248/// determine which array elements to modify for an update
249/// operation on an array field.
251 public:
252 /// Specifies list of filters
253 explicit ArrayFilters(std::initializer_list<formats::bson::Document>);
254
255 /// @cond
256 /// Retrieves an arrayFilters value
257 const formats::bson::Value& Value() const;
258 /// @endcond
259
260 private:
261 formats::bson::Value value_;
262};
263
264/// Selects count implementation to use: new aggregation-based or old cmd-based
265enum class ForceCountImpl { kAggregate, kCmd };
266
267/// Suppresses errors on querying a sharded collection with unavailable shards
269
270/// @brief Disables exception throw on server errors, should be checked manually
271/// in WriteResult
273
274/// @brief Enables tailable cursor, which block at the end of capped collections
275/// @note Automatically sets `awaitData`.
276/// @see https://docs.mongodb.com/manual/core/tailable-cursors/
277class Tailable {};
278
279/// Sets a comment for the operation, which would be visible in profile data
280class Comment {
281 public:
282 explicit Comment(std::string);
283
284 const std::string& Value() const;
285
286 private:
287 std::string value_;
288};
289
290/// @brief Specifies the server-side time limit for the operation
291/// @warning This does not set any client-side timeouts.
293 public:
294 explicit MaxServerTime(const std::chrono::milliseconds& value)
295 : value_(value) {}
296
297 const std::chrono::milliseconds& Value() const { return value_; }
298
299 private:
300 std::chrono::milliseconds value_;
301};
302
303} // namespace storages::mongo::options
304
305USERVER_NAMESPACE_END