knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
knowrob::mongo::Collection Class Reference

#include <Collection.h>

Public Member Functions

 Collection (const std::shared_ptr< Connection > &connection, std::string_view databaseName, std::string_view collectionName)
 
 Collection (const Collection &collection)
 
 ~Collection ()
 
void appendSession (bson_t *opts)
 
mongoc_client_session_t * session ()
 
auto pool ()
 
auto connection ()
 
auto client () const
 
auto coll ()
 
const auto & name () const
 
const auto & dbName () const
 
const auto & dbURI () const
 
void drop ()
 
std::vector< std::string > distinctValues (std::string_view key)
 
void removeOne (const Document &document)
 
void removeOne (const bson_oid_t &oid)
 
void removeAll (const Document &document)
 
void storeOne (const Document &document)
 
void update (const Document &query, const Document &update, bool upsert=false)
 
void evalAggregation (const bson_t *pipeline)
 
std::shared_ptr< BulkOperationcreateBulkOperation ()
 
void createAscendingIndex (const std::vector< const char * > &keys)
 
void createIndex (const std::vector< IndexKey > &keys)
 
void createTripleIndex ()
 
bool empty ()
 
 Collection (const std::shared_ptr< Connection > &connection, std::string_view databaseName, std::string_view collectionName)
 
 Collection (const Collection &collection)
 
 ~Collection ()
 
void appendSession (bson_t *opts)
 
mongoc_client_session_t * session ()
 
auto pool ()
 
auto connection ()
 
auto client () const
 
auto coll ()
 
const auto & name () const
 
const auto & dbName () const
 
const auto & dbURI () const
 
void drop ()
 
std::vector< std::string > distinctValues (std::string_view key)
 
void removeOne (const Document &document)
 
void removeOne (const bson_oid_t &oid)
 
void removeAll (const Document &document)
 
void storeOne (const Document &document)
 
void update (const Document &query, const Document &update, bool upsert=false)
 
void evalAggregation (const bson_t *pipeline)
 
std::shared_ptr< BulkOperationcreateBulkOperation ()
 
void createAscendingIndex (const std::vector< const char * > &keys)
 
void createIndex (const std::vector< IndexKey > &keys)
 
void createTripleIndex ()
 
bool empty ()
 

Detailed Description

A named collection in Mongo DB. Note that a Mongo DB instance may contain multiple databases, each of which may contain multiple collections. This class represents a single collection.

Definition at line 23 of file Collection.h.

Constructor & Destructor Documentation

◆ Collection() [1/4]

Collection::Collection ( const std::shared_ptr< Connection > &  connection,
std::string_view  databaseName,
std::string_view  collectionName 
)

Definition at line 31 of file Collection.cpp.

35  : connection_(connection),
36  session_(nullptr),
37  name_(collectionName),
38  dbName_(databaseName) {
39  client_ = pop_client(connection_->pool_);
40  coll_ = mongoc_client_get_collection(client_, dbName_.c_str(), name_.c_str());
41  db_ = mongoc_client_get_database(client_, dbName_.c_str());
42 }

◆ Collection() [2/4]

Collection::Collection ( const Collection collection)

Definition at line 44 of file Collection.cpp.

45  : connection_(other.connection_),
46  session_(nullptr),
47  name_(other.name_),
48  dbName_(other.dbName_) {
49  client_ = pop_client(connection_->pool_);
50  coll_ = mongoc_client_get_collection(client_, dbName_.c_str(), name_.c_str());
51  db_ = mongoc_client_get_database(client_, dbName_.c_str());
52 }

◆ ~Collection() [1/2]

Collection::~Collection ( )

Definition at line 54 of file Collection.cpp.

54  {
55  if (session_) {
56  mongoc_client_session_destroy(session_);
57  session_ = nullptr;
58  }
59  mongoc_database_destroy(db_);
60  mongoc_collection_destroy(coll_);
61  mongoc_client_pool_push(connection_->pool_, client_);
62 }

◆ Collection() [3/4]

knowrob::mongo::Collection::Collection ( const std::shared_ptr< Connection > &  connection,
std::string_view  databaseName,
std::string_view  collectionName 
)

◆ Collection() [4/4]

knowrob::mongo::Collection::Collection ( const Collection collection)

◆ ~Collection() [2/2]

knowrob::mongo::Collection::~Collection ( )

Member Function Documentation

◆ appendSession() [1/2]

void Collection::appendSession ( bson_t *  opts)

Append options to the session.

Parameters
optssome options

Definition at line 72 of file Collection.cpp.

72  {
73  auto s = session();
74  if (s != nullptr) {
75  bson_error_t error;
76  if (!mongoc_client_session_append(s, opts, &error)) {
77  throw MongoException("append_session", error);
78  }
79  }
80 }
mongoc_client_session_t * session()
Definition: Collection.cpp:64

◆ appendSession() [2/2]

void knowrob::mongo::Collection::appendSession ( bson_t *  opts)

Append options to the session.

Parameters
optssome options

◆ client() [1/2]

auto knowrob::mongo::Collection::client ( ) const
inline
Returns
the mongo client managing of this collection.

Definition at line 58 of file Collection.h.

58 { return client_; }

◆ client() [2/2]

auto knowrob::mongo::Collection::client ( ) const
inline
Returns
the mongo client managing of this collection.

Definition at line 58 of file Collection.h.

58 { return client_; }

◆ coll() [1/2]

auto knowrob::mongo::Collection::coll ( )
inline
Returns
the collection handle.

Definition at line 63 of file Collection.h.

63 { return coll_; }

◆ coll() [2/2]

auto knowrob::mongo::Collection::coll ( )
inline
Returns
the collection handle.

Definition at line 63 of file Collection.h.

63 { return coll_; }

◆ connection() [1/2]

auto knowrob::mongo::Collection::connection ( )
inline
Returns
the connection of this collection.

Definition at line 53 of file Collection.h.

53 { return connection_; }

◆ connection() [2/2]

auto knowrob::mongo::Collection::connection ( )
inline
Returns
the connection of this collection.

Definition at line 53 of file Collection.h.

53 { return connection_; }

◆ createAscendingIndex() [1/2]

void Collection::createAscendingIndex ( const std::vector< const char * > &  keys)

Create a search index where each key is sorted in ascending order.

Parameters
keysvector of keys

Definition at line 227 of file Collection.cpp.

227  {
228  bson_t b_keys;
229  bson_init(&b_keys);
230  for (auto key: keys) BSON_APPEND_INT32(&b_keys, key, 1);
231  createIndex_internal(b_keys);
232 }

◆ createAscendingIndex() [2/2]

void knowrob::mongo::Collection::createAscendingIndex ( const std::vector< const char * > &  keys)

Create a search index where each key is sorted in ascending order.

Parameters
keysvector of keys

◆ createBulkOperation() [1/2]

std::shared_ptr< BulkOperation > Collection::createBulkOperation ( )
Returns
a new bulk operation.

Definition at line 192 of file Collection.cpp.

192  {
193  bson_t opts = BSON_INITIALIZER;
194  BSON_APPEND_BOOL(&opts, "ordered", false);
195  // create the bulk operation
196  mongoc_bulk_operation_t *bulk =
197  mongoc_collection_create_bulk_operation_with_opts(coll_, &opts);
198  bson_destroy(&opts);
199  return std::make_shared<BulkOperation>(bulk);
200 }

◆ createBulkOperation() [2/2]

std::shared_ptr<BulkOperation> knowrob::mongo::Collection::createBulkOperation ( )
Returns
a new bulk operation.

◆ createIndex() [1/2]

void Collection::createIndex ( const std::vector< IndexKey > &  keys)

Create a search index.

Parameters
keysvector of keys

Definition at line 234 of file Collection.cpp.

234  {
235  bson_t b_keys;
236  bson_init(&b_keys);
237  for (auto &key: keys) {
238  if (key.type == IndexType::ASCENDING) {
239  BSON_APPEND_INT32(&b_keys, key.value.c_str(), 1);
240  } else {
241  BSON_APPEND_INT32(&b_keys, key.value.c_str(), -1);
242  }
243  }
244  createIndex_internal(b_keys);
245 }

◆ createIndex() [2/2]

void knowrob::mongo::Collection::createIndex ( const std::vector< IndexKey > &  keys)

Create a search index.

Parameters
keysvector of keys

◆ createTripleIndex() [1/2]

void Collection::createTripleIndex ( )

Create a search index for s/p/o fields.

Definition at line 247 of file Collection.cpp.

247  {
248  // Some notes on indexing:
249  // - Compound indexes contain their prefixes as sub-indexes.
250  // e.g. {s: 1, p: 1} contains {s: 1} and {s: 1, p: 1}.
251  // - Keep equality matches first in the index.
252  // @see https://www.mongodb.com/docs/manual/tutorial/equality-sort-range-rule/#std-label-esr-indexing-rule
253  // - Optional fields receive null values for documents that do not contain them.
254  // - The context fields are not indexed here as there are too many of them.
255  // Assuming each of them may appear as a variable in a query, too many indexes would be needed.
256  // If they are not allowed to appear as variables, one could append them to the existing indexes
257  // (still causing a lot of indexes, as many prefixes exist in large compound indexes).
258 
259  createAscendingIndex({"s", "p"});
260  createAscendingIndex({"s", "p*"});
261  createAscendingIndex({"s", "o", "p"});
262  createAscendingIndex({"s", "o", "p*"});
263  createAscendingIndex({"s", "p", "o*"});
264  createAscendingIndex({"o", "p"});
265  createAscendingIndex({"o", "p*"});
266  createAscendingIndex({"o*"});
267  createAscendingIndex({"p", "o*"});
268  createAscendingIndex({"p*"});
269 }
void createAscendingIndex(const std::vector< const char * > &keys)
Definition: Collection.cpp:227

◆ createTripleIndex() [2/2]

void knowrob::mongo::Collection::createTripleIndex ( )

Create a search index for s/p/o fields.

◆ dbName() [1/2]

const auto& knowrob::mongo::Collection::dbName ( ) const
inline
Returns
the name of the database.

Definition at line 73 of file Collection.h.

73 { return dbName_; }

◆ dbName() [2/2]

const auto& knowrob::mongo::Collection::dbName ( ) const
inline
Returns
the name of the database.

Definition at line 73 of file Collection.h.

73 { return dbName_; }

◆ dbURI() [1/2]

const auto& knowrob::mongo::Collection::dbURI ( ) const
inline
Returns
the URI string used to connect to the database.

Definition at line 78 of file Collection.h.

78 { return connection_->uri_string_; }

◆ dbURI() [2/2]

const auto& knowrob::mongo::Collection::dbURI ( ) const
inline
Returns
the URI string used to connect to the database.

Definition at line 78 of file Collection.h.

78 { return connection_->uri_string_; }

◆ distinctValues() [1/2]

std::vector< std::string > Collection::distinctValues ( std::string_view  key)
Parameters
keythe name of a field in mongo documents.
Returns
a list of distinct values for the given key.

Definition at line 89 of file Collection.cpp.

89  {
90  bson_error_t err;
91  bson_t reply;
92  bson_t *command = BCON_NEW("distinct", BCON_UTF8(name_.c_str()), "key", BCON_UTF8(key.data()));
93  bool success = mongoc_database_command_simple(
94  db_, command, nullptr, &reply, &err);
95  if (!success) {
96  bson_destroy(command);
97  bson_destroy(&reply);
98  throw MongoException("distinct_failed", err);
99  }
100 
101  std::vector<std::string> values;
102  bson_iter_t iter;
103  if (bson_iter_init(&iter, &reply)) {
104  const bson_value_t *value;
105  if (bson_iter_find(&iter, "values") && BSON_ITER_HOLDS_ARRAY(&iter)) {
106  bson_iter_t array;
107  bson_iter_recurse(&iter, &array);
108  while (bson_iter_next(&array)) {
109  value = bson_iter_value(&array);
110  values.emplace_back(value->value.v_utf8.str);
111  }
112  }
113  }
114  bson_destroy(command);
115  bson_destroy(&reply);
116  return values;
117 }

◆ distinctValues() [2/2]

std::vector<std::string> knowrob::mongo::Collection::distinctValues ( std::string_view  key)
Parameters
keythe name of a field in mongo documents.
Returns
a list of distinct values for the given key.

◆ drop() [1/2]

void Collection::drop ( )

Drop this collection, removing all document it contains.

Definition at line 82 of file Collection.cpp.

82  {
83  bson_error_t err;
84  if (!mongoc_collection_drop(coll_, &err)) {
85  throw MongoException("drop_failed", err);
86  }
87 }

◆ drop() [2/2]

void knowrob::mongo::Collection::drop ( )

Drop this collection, removing all document it contains.

◆ empty() [1/2]

bool Collection::empty ( )
Returns
true is this collection is empty.

Definition at line 271 of file Collection.cpp.

271  {
272  bson_t *opts = BCON_NEW("limit", BCON_INT64(1));
273  bson_t filter = BSON_INITIALIZER;
274  bson_error_t error;
275  int64_t count;
276 
277  count = mongoc_collection_count_documents(
278  coll_,
279  &filter,
280  opts,
281  nullptr,
282  nullptr,
283  &error);
284  bson_destroy(opts);
285  bson_destroy(&filter);
286 
287  return count == 0;
288 }

◆ empty() [2/2]

bool knowrob::mongo::Collection::empty ( )
Returns
true is this collection is empty.

◆ evalAggregation() [1/2]

void Collection::evalAggregation ( const bson_t *  pipeline)

Evaluate an aggregation pipeline without forwarding any resulting documents. e.g. useful for pipelines with $merge stage.

Parameters
pipelinea pipeline

Definition at line 173 of file Collection.cpp.

173  {
174  auto cursor = mongoc_collection_aggregate(
175  coll_,
176  MONGOC_QUERY_NONE,
177  pipeline,
178  nullptr,
179  nullptr);
180  // make sure cursor has no error after creation
181  bson_error_t err;
182  if (mongoc_cursor_error(cursor, &err)) {
183  mongoc_cursor_destroy(cursor);
184  throw MongoException("cursor_error", err);
185  }
186  // process the query (ignore results)
187  const bson_t *cursor_doc;
188  while (mongoc_cursor_next(cursor, &cursor_doc)) {}
189  mongoc_cursor_destroy(cursor);
190 }

◆ evalAggregation() [2/2]

void knowrob::mongo::Collection::evalAggregation ( const bson_t *  pipeline)

Evaluate an aggregation pipeline without forwarding any resulting documents. e.g. useful for pipelines with $merge stage.

Parameters
pipelinea pipeline

◆ name() [1/2]

const auto& knowrob::mongo::Collection::name ( ) const
inline
Returns
the name of the collection.

Definition at line 68 of file Collection.h.

68 { return name_; }

◆ name() [2/2]

const auto& knowrob::mongo::Collection::name ( ) const
inline
Returns
the name of the collection.

Definition at line 68 of file Collection.h.

68 { return name_; }

◆ pool() [1/2]

auto knowrob::mongo::Collection::pool ( )
inline
Returns
the client pool of this collection.

Definition at line 48 of file Collection.h.

48 { return connection_->pool_; }

◆ pool() [2/2]

auto knowrob::mongo::Collection::pool ( )
inline
Returns
the client pool of this collection.

Definition at line 48 of file Collection.h.

48 { return connection_->pool_; }

◆ removeAll() [1/2]

void Collection::removeAll ( const Document document)

Remove all matching JSON documents from this collection.

Parameters
documenta document pattern.

Definition at line 131 of file Collection.cpp.

131  {
132  remove(document, MONGOC_REMOVE_NONE);
133 }

◆ removeAll() [2/2]

void knowrob::mongo::Collection::removeAll ( const Document document)

Remove all matching JSON documents from this collection.

Parameters
documenta document pattern.

◆ removeOne() [1/4]

void Collection::removeOne ( const bson_oid_t &  oid)

Remove a single matching document from this collection.

Parameters
oida document oid.

Definition at line 135 of file Collection.cpp.

135  {
136  removeOne(Document(BCON_NEW("_id", BCON_OID(&oid))));
137 }
void removeOne(const Document &document)
Definition: Collection.cpp:139

◆ removeOne() [2/4]

void knowrob::mongo::Collection::removeOne ( const bson_oid_t &  oid)

Remove a single matching document from this collection.

Parameters
oida document oid.

◆ removeOne() [3/4]

void Collection::removeOne ( const Document document)

Remove a single matching document from this collection.

Parameters
documenta document pattern.

Definition at line 139 of file Collection.cpp.

139  {
140  remove(document, MONGOC_REMOVE_SINGLE_REMOVE);
141 }

◆ removeOne() [4/4]

void knowrob::mongo::Collection::removeOne ( const Document document)

Remove a single matching document from this collection.

Parameters
documenta document pattern.

◆ session() [1/2]

mongoc_client_session_t * Collection::session ( )
Returns
the session handle.

Definition at line 64 of file Collection.cpp.

64  {
65  if (!session_) {
66  bson_error_t error;
67  session_ = mongoc_client_start_session(client_, nullptr, &error);
68  }
69  return session_;
70 }

◆ session() [2/2]

mongoc_client_session_t* knowrob::mongo::Collection::session ( )
Returns
the session handle.

◆ storeOne() [1/2]

void Collection::storeOne ( const Document document)

Store one document into this collection.

Parameters
documenta JSON document.

Definition at line 119 of file Collection.cpp.

119  {
120  bson_error_t err;
121  if (!mongoc_collection_insert(
122  coll_,
123  INSERT_NO_VALIDATE_FLAG,
124  document.bson(),
125  nullptr,
126  &err)) {
127  throw MongoException("insert_failed", err);
128  }
129 }
bson_t * bson() const
Definition: Document.h:27

◆ storeOne() [2/2]

void knowrob::mongo::Collection::storeOne ( const Document document)

Store one document into this collection.

Parameters
documenta JSON document.

◆ update() [1/2]

void Collection::update ( const Document query,
const Document update,
bool  upsert = false 
)

Update all existing documents matching the document pattern.

Parameters
querya document pattern.
updatethe update document.
upsertif true, create a new document if no match is found.

Definition at line 156 of file Collection.cpp.

156  {
157  bson_error_t err;
158 
159  int flags = UPDATE_NO_VALIDATE_FLAG;
160  if (upsert) flags |= MONGOC_UPDATE_UPSERT;
161 
162  if (!mongoc_collection_update(
163  coll_,
164  (mongoc_update_flags_t) flags,
165  query.bson(),
166  update.bson(),
167  nullptr,
168  &err)) {
169  throw MongoException("update_failed", err);
170  }
171 }
void update(const Document &query, const Document &update, bool upsert=false)
Definition: Collection.cpp:156

◆ update() [2/2]

void knowrob::mongo::Collection::update ( const Document query,
const Document update,
bool  upsert = false 
)

Update all existing documents matching the document pattern.

Parameters
querya document pattern.
updatethe update document.
upsertif true, create a new document if no match is found.

The documentation for this class was generated from the following files: