请选择 进入手机版 | 继续访问电脑版
楼主: Nicolle
4415 27

Sams Teach Yourself NoSQL with MongoDB in 24 Hours, [推广有奖]

Lisrelchen 发表于 2015-7-17 10:56:39 |显示全部楼层 |坛友微信交流群
15.Summary

In this hour, you used the PHP MongoDB driver to add, manipulate, and remove documents from a collection in your PHP applications. You used several different methods on the MongoCollection object to change data in a collection.

The insert() method adds new documents. The remove() method deletes documents. The save() method updates a single document.

The update() method can be used in multiple ways. You can have it update a single document or multiple documents. You can also apply the upsert option to insert new documents into the collection if none matches to be updated.




使用道具

Lisrelchen 发表于 2015-7-17 10:59:46 |显示全部楼层 |坛友微信交流群
Getting the Documents from MongoDB Using Python

The Collection object provides the find() and find_one() methods, similar to what you saw in the MongoDB shell. These methods find a single document or multiple documents.


When you call find_one(), the server returns a single document as a Dictionary object. You can then use the object in your application as needed. For example:

  1. doc = myColl.find_one()
复制代码

The find() method on the Collection object returns a Cursor object that only represents the documents found and does not initially retrieve them. The Cursor object can be iterated in a few different ways.

You can use a for loop method to determine whether you have reached the end of the cursor. For example:

  1. cursor = myColl.find()
  2. for doc in cursor:
  3.   print (doc)
复制代码

Because Python treats the cursor as a list, you can also use Python slice syntax to access portions of the cursor. For example, the following finds all documents and then displays documents 5–10:

  1. cursor = collection.find()
  2. slice = cursor[5:10]
  3. for doc in slice:
  4.   print (doc)
复制代码

使用道具

Lisrelchen 发表于 2015-7-17 11:00:42 |显示全部楼层 |坛友微信交流群
Counting Documents in Python

When accessing document sets in MongoDB from Python, you might want to only get a count first before deciding to retrieve a set of documents. Performing a count is much less intensive on the MongoDB server and client because the actual documents do not need to be transferred.

The count() method on the Cursor object enables you to get a simple count of documents that are represented. For example, the following code uses the find() method to get a Cursor object and then uses the count() method to get the number of items:

  1. cursor = wordsColl.find()
  2. itemCount = cursor.count()
复制代码

The value of itemCount is the number of words that match the find() operation.


使用道具

Lisrelchen 发表于 2015-7-17 11:01:57 |显示全部楼层 |坛友微信交流群
Sorting Result Sets in Python

An important aspect of retrieving documents from a MongoDB database is the capability to get them in a sorted order. This is especially helpful if you are retrieving only a certain number of results, such as the top 10, or if you are paging the requests. The options object provides the sort option, which enables you to specify the sort order and direction of one or more fields in the document.

The sort() method on the Cursor object enables you to specify fields to sort the documents represented in the cursor and return them in that order. The sort() method accepts a list of tuples that provide a (key,order) pair. The key is the field name to sort on, and order is 1 for ascending and -1 for descending.

For example, to sort on the name field in ascending order, you would use

  1. sorter = [('name', 1)]
  2. cursor = myCollection.find()
  3. cursor.sort(sorter)
复制代码

You can use multiple fields in the object passed to the sort() method, and the documents will be sorted on those fields. You can also apply sort() multiple times on the same cursor to sort on different fields. For example, to sort on the name field descending first and then the value field ascending, you could use

  1. sorter = [('name', 1), ('value', -1)];
  2. cursor = myCollection.find()
  3. cursor.sort(sorter)
复制代码

you could use

  1. sorter1 = [('name', 1)]
  2. sorter2 = [('value', -1)]
  3. cursor = myCollection.find()
  4. cursor = cursor.sort(sorter1)
  5. cursor.sort(sorter2)
复制代码

使用道具

Lisrelchen 发表于 2015-7-17 11:03:47 |显示全部楼层 |坛友微信交流群
Limiting Results by Size in Python

The simplest method of limiting the amount of data returned in a find() or other query request is to use the limit() method on the Cursor object returned by the find() operation. The limit() method limits the Cursor object so that it returns only a fixed number of items. This can save you from accidentally retrieving more objects than your application can handle.


For example, the following Python code displays only the first 10 documents in a collection, even though there could be thousands:

  1. cursor = wordsColl.find()
  2. cursor.limit(10)
  3. for word in cursor:
  4.   print (word)
复制代码


使用道具

Lisrelchen 发表于 2015-7-17 11:05:11 |显示全部楼层 |坛友微信交流群
Finding Distinct Field Value in Python

A useful query against a MongoDB collection is to get a list of the distinct values for a single field in a set of documents. Distinct means that even though thousands of documents exist, you want to know only the unique values.

The distinct() method on Collection and Cursor objects enables you to find a list of distinct values for a specific field. The syntax for the distinct() method follows:

distinct(key)

The key parameter is the string value of the field name you want to get values for. You can specify subdocuments using dot syntax, such as stats.count. If you want to get distinct values based on a subset of documents, you need to first generate a Cursor object with a query parameter and then call distinct() on that Cursor object.

For example, to find the distinct last names of users over 65 in a collection that has documents with first, last, and age fields, you would use the following operation:

  1. query = {'age' : {'$gt' : 65}}
  2. cursor = myCollection.find(query)
  3. lastNames = cursor.distinct('last')The distinct() method returns an array with the distinct values for the field specified. For example:["Smith", "Jones", ...]
复制代码


使用道具

Lisrelchen 发表于 2015-7-17 11:06:35 |显示全部楼层 |坛友微信交流群
Grouping Results of Find Operations in Python Applications

When performing operations on large datasets in Python, grouping the results based on the distinct values of one or more fields in a document is often useful. This can be done in code after retrieving the documents, but it is much more efficient to have the MongoDB server do it for you as part of a single request that is already iterating though the documents.

In Python, to group the results of a query, you can use the group() method on the Collection object. The group request collects all the documents that match a query, adds a group object to an array based on distinct values of a set of keys, performs operations on the group objects, and returns the array of group objects.

The syntax for the group() methods follows:

  1. group({key, cond , initial, reduce, [finalize]})
复制代码

The key, cond, and initial parameters are a Dictionary object that define the fields to use, query, and limit documents and initial value settings. The reduce and finalize methods are String objects that contain a string form of a JavaScript function that is run on the server to reduce and finalize the results. See Hour 9, “Utilizing the Power of Grouping, Aggregation, and Map Reduce,” for more information on these parameters.

For illustration, the following code implements a basic grouping by generating the key, cond, and initial objects and passing in a reduce function as a string:

  1. key = {'first' : True }cond = {'first' : 'a', 'size': 5}
  2. initial = {'count' : 0}
  3. reduce = "function (obj, prev) { prev.count++; }"
  4. results = collection.group(key, cond, initial, reduce)
复制代码

The result from the group method is a List that contains the groupings. To illustrate the results, the following code displays the items in the group one at a time:

  1. for result in results:
  2.     print (result)
复制代码

使用道具

dsawx 发表于 2015-7-23 11:22:30 |显示全部楼层 |坛友微信交流群
谢谢分享。

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-18 15:44