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)
 
(9 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">
+
<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()[0])
+
db.world.aggregate([{"$match":{}}])
pp.pprint(list(db.world.find().limit(1))[0])
+
</pre>
pp.pprint(list(db.world.aggregate([{"$limit":1}]))[0])
+
</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>
 
</pre>
 
</div>
 
</div>
  
<div class=q data-lang="py3">Returning the <b>n</b>th document
+
<div class="q" data-lang="mongo">Returning the last document
<pre class=def>
+
<pre class="def">
n = 50;
+
db.world.find()[db.world.count()-1]
pp.pprint(db.world.find_one()[n-1])
+
db.world.find().skip(db.world.count()-1).limit(1)
pp.pprint(db.world.find()[n-1])
+
db.world.aggregate([{"$skip":db.world.count()-1},{"$limit":1}])
pp.pprint(list(db.world.find().skip(n-1).limit(1))[0])
 
pp.pprint(list(db.world.aggregate([{"$skip":n-1},{"$limit":1}]))[0])
 
 
</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}])