Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

Difference between revisions of "Returning documents"

From NoSQLZoo
Jump to: navigation, search
(Convert py3 -> mongo)
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
<pre class=setup>
 
#ENCODING
 
import io
 
import sys
 
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16')
 
#MONGO
 
from pymongo import MongoClient
 
client = MongoClient()
 
client.progzoo.authenticate('scott','tiger')
 
db = client['progzoo']
 
#PRETTY
 
import pprint
 
pp = pprint.PrettyPrinter(indent=4)
 
#CODE
 
from bson.code import Code
 
</pre>
 
 
{{TopTenTips}}
 
{{TopTenTips}}
 
<div style='height:25em;'>
 
<div style='height:25em;'>
 
</div>
 
</div>
<div class=q data-lang="py3">MapReduce
+
<div class="q" data-lang="mongo">Return all documents
<pre class=def>
+
<pre class="def">
pp.pprint(db.world.find_one())
+
db.world.find()
pp.pprint(db.world.find()[1])
+
db.world.aggregate([{"$match":{}}])
pp.pprint(db.world.find().limit(1))
+
</pre>
pp.pprint(db.world.aggregate([{"$limit":1}])
+
</div>
 +
 
 +
<div class="q" data-lang="mongo">Returning the first document
 +
<pre class="def">
 +
db.world.findOne()
 +
db.world.find()[0]
 +
db.world.find().limit(1)
 +
db.world.aggregate([{"$limit":1}])
 +
</pre>
 +
</div>
 +
 
 +
<div class="q" data-lang="mongo">Returning the '''n'''th document
 +
<pre class="def">
 +
let n = 50;
 +
db.world.find()[n-1]
 +
db.world.find().skip(n-1).limit(1)
 +
db.world.aggregate([{"$skip":n-1},{"$limit":1}])
 +
</pre>
 +
</div>
 +
 
 +
<div class="q" data-lang="mongo">Returning the last document
 +
<pre class="def">
 +
db.world.find()[db.world.count()-1]
 +
db.world.find().skip(db.world.count()-1).limit(1)
 +
db.world.aggregate([{"$skip":db.world.count()-1},{"$limit":1}])
 
</pre>
 
</pre>
 
</div>
 
</div>

Latest revision as of 00:13, 9 April 2018

Return all documents
db.world.find()
db.world.aggregate([{"$match":{}}])
Returning the first document
db.world.findOne()
db.world.find()[0]
db.world.find().limit(1)
db.world.aggregate([{"$limit":1}])
Returning the nth document
let n = 50;
db.world.find()[n-1]
db.world.find().skip(n-1).limit(1)
db.world.aggregate([{"$skip":n-1},{"$limit":1}])
Returning the last document
db.world.find()[db.world.count()-1]
db.world.find().skip(db.world.count()-1).limit(1)
db.world.aggregate([{"$skip":db.world.count()-1},{"$limit":1}])