Database Reference
In-Depth Information
Now that the database has been selected, you can select your MongoDB collection in exactly the same way.
Because you've already stored the database name under the db dictionary, you can use that to select the collection's
name; it is called items in this case:
>>> collection = db.items
Inserting Data
All that remains is to define the document by storing it in a dictionary. Let's take the preceding example and insert
that into the shell:
>>> item = {
... "Type" : "Laptop",
... "ItemNumber" : "1234EXD",
... "Status" : "In use",
... "Location" : {
... "Department" : "Development",
... "Building" : "2B",
... "Floor" : 12,
... "Desk" : 120101,
... "Owner" : "Anderson, Thomas"
... },
... "Tags" : ["Laptop","Development","In Use"]
... }
Once you define the document, you can insert it using the same insert() function that is available in the
MongoDB shell:
>>> collection.insert(item)
ObjectId('4c57207b4abffe0e0c000000')
That's all there is to it: you define the document and insert it using the insert() function.
There's one more interesting trick you can take advantage of when inserting documents: inserting multiple
documents at the same time. You can do this by specifying both documents in a single dictionary, and then inserting
that document. The result will return two ObjectId values; pay careful attention to how the brackets are used in the
following example:
>>> two = [{
... "Type" : "Laptop",
... "ItemNumber" : "2345FDX",
... "Status" : "In use",
... "Location" : {
... "Department" : "Development",
... "Building" : "2B",
... "Floor" : 12,
... "Desk" : 120102,
... "Owner" : "Smith, Simon"
... },
... "Tags" : ["Laptop","Development","In Use"]
... },
 
Search WWH ::




Custom Search