Tuesday, March 21, 2017

MongoDB query practice

Here is the data
{"id":1, "priority":10}
{"id":2, "priority":9}
{"id":3, "priority":11} 
Now, the input parameter is id=3, and I want to get the records which id is 3 and the record which priority is just before the record which id=3. 
{"id":3, "priority":11}
{"id":1, "priority":10}
if the input parameter id=2, it shall return 
{"id":2, "priority":9}
If the input parameter id=1, it shall return 
{"id":1, "priority":10}
{"id":2, "priority":9}
Can it be done in one query?

delete records

db.users.deleteMany({ status : "A" })

updateMany

this is like the sql update with where clause, which update a bunch of documents satisfy the conditions.
db.restaurant.updateMany(
      { violations: { $gt: 4 } },
      { $set: { "Review" : true } }
   )

count and sort by count result

db.quote.aggregate([{$group: {_id:"$Symbol", quoteCount:{$sum:1}}, {$sort:{quoteCount:-1}}  }])

contains

db.users.findOne({"username" : {$regex : ".*son.*"}});

sort and get last N result

db.collection.find({}).sort("_id", -1).limit(N)
be careful, you cannot put in sort({"id": -1}), that will give you the error.

find documents which don't contain one field

db.prediction.find({isCorrect:{$exists:false}})

create unique index

db.quote.createIndex({"Symbol":1,"Date":1}, {unique:true})

No comments:

Post a Comment