Skip to content

Synchronous Client Tutorial

Rostyslav Dzinko edited this page Nov 21, 2015 · 2 revisions

nimongo.mongo.Mongo synchronous client performs interaction with MongoDB over network using sockets and blocking I/O which stops the thread it is used on from executing while MongoDB operation is not finished: either data is sent over network (insert, update, remove), or query (find) is done, and answer (or portion of it) is waited for.

Mongo synchronous client is thread-safe. It uses simple Lock when executing commands and queries.

import oids

import nimongo.bson  ## MongoDB BSON serialization/deserialization
import nimongo.mongo ## MongoDB client

## Create new Mongo client
var m = newMongo().slaveOk(true).allowPartial(false)

## Connect to Mongo server
let connectResult = m.connect()

## Specify collection
let collection = m["db"]["collectionName"]

## Create new bson document
let doc = %*{
  "name": "John"
}

## Insert document into DB
collection.insert(doc)

## Update [single] document
let reply = collection.update(%*{
  "name": "John"
}, %*{
  "$set": {
    "surname": "Smith"
  }
})

# Check command execution status
if reply.ok:
  echo "Modified a document."

## Delete multiple documents
let removeResult = collection.remove(%*{"name": "John"})

## Check how many documents were removed
if removeResult.ok:
  echo "Removed ", removeResult.n, " documents."

## Delete single document
collection.remove(%{"name": "John"}, limit=1)

## Fetch one document from DB returning only one field: "name".
let fetched = collection.find(%*{"name": "John"}, @["name"]).one()

## Fetch all matching documents from DB receiving seq[Bson]
let documents = collection.find(%*{"name": "John"}).all()

## Fetch all matching documents as a iterator
for document in collection.find(%*{"name": "John"}).items():
  echo document
Clone this wiki locally