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
m (40166222 moved page Template:Returning the first document to Returning the first document without leaving a redirect)
(Convert py3 -> mongo)
 
(14 intermediate revisions by the same user not shown)
Line 1: Line 1:
<pre class=setup>
+
{{TopTenTips}}
#ENCODING
+
<div style='height:25em;'>
import io
+
</div>
import sys
+
<div class="q" data-lang="mongo">Return all documents
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16')
+
<pre class="def">
#MONGO
+
db.world.find()
from pymongo import MongoClient
+
db.world.aggregate([{"$match":{}}])
client = MongoClient()
+
</pre>
client.progzoo.authenticate('scott','tiger')
+
</div>
db = client['progzoo']
+
 
#PRETTY
+
<div class="q" data-lang="mongo">Returning the first document
import pprint
+
<pre class="def">
pp = pprint.PrettyPrinter(indent=4)
+
db.world.findOne()
#CODE
+
db.world.find()[0]
from bson.code import Code
+
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>
 
</pre>
{{TopTenTips}}
+
</div>
<div class='extra_space' style='width:1em; height:20em;'></div>
+
 
<div class=q data-lang="py3">MapReduce
+
<div class="q" data-lang="mongo">Returning the last document
<pre class=def>
+
<pre class="def">
pp.pprint(db.world.find_one())
+
db.world.find()[db.world.count()-1]
pp.pprint(db.world.find()[1])
+
db.world.find().skip(db.world.count()-1).limit(1)
pp.pprint(db.world.find().limit(1))
+
db.world.aggregate([{"$skip":db.world.count()-1},{"$limit":1}])
pp.pprint(db.world.aggregate([{"$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}])