100+ results for 'MongoDBObject find lang:Scala'

Not the results you expected?

DataStoreOperations.scala (https://github.com/SINTEF-9012/sensapp.git) Scala · 181 lines

47

48 import com.mongodb.casbah.Imports._

49 import com.mongodb.casbah.commons.MongoDBObjectBuilder

50 import com.mongodb.util.JSON

51

83 */

84 def pull(id: Criterion): Option[T] = {

85 val dbResult = _collection.findOne(MongoDBObject(id._1 -> id._2))

86 dbResult match {

87 case Some(dbObj) => Some(toDomainObject(dbObj))

114 */

115 def retrieve(criteria: List[(String, Any)]): List[T] = {

116 val prototype = MongoDBObject.newBuilder

117 criteria foreach { c => prototype += (c._1 -> c._2) }

118 _collection.find(prototype.result).toList map { toDomainObject(_) }

MongoDBSpecification.scala (https://github.com/derzzle/casbah.git) Scala · 150 lines

26 import org.specs2.matcher.Matchers._

27 import com.mongodb.casbah.util.Logging

28 import com.mongodb.casbah.commons.MongoDBObject

29 import javax.management.remote.rmi._RMIConnection_Stub

30

35 trait CasbahSpecification extends Specification with DBObjectMatchers with Logging {

36 implicit val sizedOptDBObj = new Sized[Option[DBObject]] {

37 def size(t: Option[DBObject]) = t.getOrElse(MongoDBObject.empty).size

38 }

39

75 def beDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[DBObject], " is a DBObject", " is not a DBObject")

76

77 def beMongoDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBObject], " is a MongoDBObject", " is not a MongoDBObject")

78

79 def beMongoDBList: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBList], " is a MongoDBList", " is not a MongoDBList")

ResponseServiceTest.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 128 lines

5 import org.scalatest.matchers.ShouldMatchers

6 import org.scalatest.{BeforeAndAfterEach, FunSuite}

7 import com.mongodb.casbah.commons.MongoDBObject

8 import com.mongodb.casbah.MongoConnection

9 import com.cyrusinnovation.inquisition.response.mongodb.MongoResponseRepository

24

25 override def beforeEach() {

26 db("questions").remove(MongoDBObject())

27 }

28

100 }

101

102 test("can find question by id") {

103 val question = createSavedQuestion()

104 val response = createSavedResponse(question)

MongoTagsRepositoryTest.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 176 lines

8 import org.junit.runner.RunWith

9 import org.scalatest.junit.JUnitRunner

10 import com.mongodb.casbah.commons.MongoDBObject

11

12 @RunWith(classOf[JUnitRunner])

19

20 override def beforeEach() {

21 db("tags").remove(MongoDBObject())

22 db("questions").remove(MongoDBObject())

28

29

30 test("find all unqiue question tags") {

31 questionRepository.save(uniqueQuestion().copy(tags = List("java", "spring")));

32 questionRepository.save(uniqueQuestion().copy(tags = List("scala", "spring")));

33 questionRepository.findQuestionCount() should equal(2)

34 val uniqueTags = tagRepository.findUniqueTagNamesOrderedByTagName()

MongoTagRepository.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 93 lines

17 tags.ensureIndex(MongoDBObject("_id" -> 1))

18 questions.ensureIndex(MongoDBObject("tags" -> 1))

19

20 def db2question(dbObj: DBObject): Question = {

29 def findQuestionsByTag(tag: String): List[Question] = {

30 val results = questions.find(MongoDBObject("tags" -> tag))

31 results.map(db2question).toList

32 }

57 }"""

58

59 val commandBuilder = MongoDBObject.newBuilder

60 commandBuilder += "mapreduce" -> "questions"

61 commandBuilder += "map" -> mapFunction

64 db.command(commandBuilder.result())

65

66 val tagList = tags.find().sort(MongoDBObject("value" -> -1)).limit(numberToRetreive)

67 val map = tagList map { t => t.getAs[String]("_id").get -> t.getAs[Double]("value").get }

68

MongoQuestionRepositoryTest.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 324 lines

8 import org.junit.runner.RunWith

9 import org.scalatest.junit.JUnitRunner

10 import com.mongodb.casbah.commons.MongoDBObject

11 import java.lang.String

12 import org.bson.types.ObjectId

20

21 override def beforeEach() {

22 db("questions").remove(MongoDBObject())

23 }

24

33 savedQuestion.id should not be (None)

34 savedQuestion.id should be('defined)

35 val retrievedQuestion = repository.findById(savedQuestion.id.get).get

36 retrievedQuestion.id should be(savedQuestion.id)

37 }

User.scala (https://gitlab.com/guodman/webcbv) Scala · 122 lines

59

60 def save = {

61 var builder = MongoDBObject.newBuilder

62 builder += "_id" -> _id

63 builder += "username" -> username

92

93 def get(id: ObjectId): User = {

94 dbCollection.findOneByID(id).map({ dbobj => factory(dbobj) }).getOrElse[User](null)

95 }

96

104

105 def getByUsername(username: String): User = {

106 val r = dbCollection.findOne(MongoDBObject("username" -> ("(?i)" + username).r))

107 return r.map(factory(_)).headOption.getOrElse[User](null)

108 }

Mr00.scala (http://scaly.googlecode.com/svn/trunk/) Scala · 131 lines

31 import scaly.parabond.mr.MapReduce

32 import com.mongodb.casbah.MongoConnection

33 import com.mongodb.casbah.commons.MongoDBObject

34 import com.mongodb.casbah.MongoCursor

35 import scaly.parabond.util.MongoHelper

83 val portfsCollecton = mongo("Portfolios")

84

85 val portfsQuery = MongoDBObject("id" -> portfId)

86

87 val portfsCursor : MongoCursor = portfsCollecton.find(portfsQuery)

94

95 val value = bondIds.foldLeft(0.0) { (sum, id) =>

96 val bondsQuery = MongoDBObject("id" -> id)

97

98 val bondsCursor: MongoCursor = bondsCollection.find(bondsQuery)

MongoDbAccess.scala (https://github.com/jmrowe/PartsDbWebApp.git) Scala · 115 lines

25

26 /*private val incrementUniqueId = (currentId: Long) => {

27 val newIdObject = MongoDBObject("uniqueId" -> (currentId + 1))

28 val findIdObjectQuery = "uniqueId" $exists true

29 mongoCollection.findOne(findIdObjectQuery) match {

30 case None => mongoCollection += newIdObject

31 case _ => mongoCollection.findAndModify(findIdObjectQuery, newIdObject)

42 */ /*

43 override def nextId(): Long = {

44 val findOneQuery = mongoCollection.findOne(idQuery)

45 val idValue = findOneQuery match {

55 }

56

57 private val addressQuery = (addressId: AddressId) => MongoDBObject("addressId" -> MongoDBObject("id" -> addressId.id))

58

59 private val addressesQuery = () => "addressId" $exists true

MongoQuestionRepository.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 81 lines

26 case Some(id: String) => {

27 val dbObj = grater[Question].asDBObject(question)

28 questions.update(MongoDBObject("_id" -> new ObjectId(id)), dbObj, false, false, WriteConcern.Safe)

29 question.copy(id = Some(dbObj("id").toString))

30 }

37 }

38

39 def findById(id: String): Option[Question] = {

40 val result: Option[DBObject] = questions.findOneByID(new ObjectId(id))

46 def findRecent(limit: Int): List[Question] = {

47 val results = questions.find().limit(limit) map (db2question)

48 results.toList

49 }

71 def findResponseQuestion(responseId: String): Option[Question] = {

72 questions.findOne(MongoDBObject("responses.id" -> responseId))

73 .map(db2question(_))

74 .toList

FileStoreSpec.scala (https://github.com/delving/dos.git) Scala · 87 lines

1 import com.mongodb.casbah.commons.MongoDBObject

2 import controllers.dos._

3 import java.io.{ByteArrayInputStream, File}

41 }

42

43 it should "find back files by upload UID" in {

44 val fetched: Seq[StoredFile] = FileUpload.getFilesForUID(TEST_UID)

45 fetched.length should equal(1)

50 it should "attach uploaded files to an object, given an upload UID and an object ID" in {

51 FileUpload.markFilesAttached(TEST_UID, TEST_OID)

52 val file = fileStore.findOne(MongoDBObject(ITEM_POINTER_FIELD -> TEST_OID))

53 file should not equal (None)

54 FileUpload.getFilesForUID(TEST_UID).length should equal(0)

store.scala (https://github.com/softprops/hush.git) Scala · 82 lines

7 object Store {

8 import com.mongodb.casbah.commons.Imports.ObjectId

9 import com.mongodb.casbah.commons.{MongoDBObject => Obj, MongoDBList => ObjList}

10 import com.mongodb.casbah.{MongoCollection}

11 import com.mongodb.{BasicDBList, DBObject}

78 val query = "loc".$within $center ((lat, lon), 0.01)

79 println(query)

80 f(toPlaces(c.find( query )))

81 }

82 }

QuestionServiceImplTest.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 203 lines

8 import org.scalatest.junit.JUnitRunner

9 import com.cyrusinnovation.inquisition.questions.mongodb.{MongoTestConstants, MongoQuestionRepository}

10 import com.mongodb.casbah.commons.MongoDBObject

11 import java.security.InvalidParameterException

12 import java.lang.String

23

24 override def beforeEach() {

25 db("questions").remove(MongoDBObject())

26 }

27

36 savedQuestion.id should not be (None)

37 savedQuestion.id should be('defined)

38 val retrievedQuestion = service.findById(savedQuestion.id.get)

39 retrievedQuestion.id should be(savedQuestion.id)

40 }

ScalaTestHelpers.scala (git://github.com/mongodb/casbah.git) Scala · 126 lines

26

27 protected def someField(map: Option[DBObject], k: String) = if (k.indexOf('.') < 0) {

28 map.getOrElse(MongoDBObject.empty).getAs[AnyRef](k)

29 } else {

30 map.getOrElse(MongoDBObject.empty).expand[AnyRef](k)

FeedBotSpec.scala (https://github.com/HendraWijaya/syndor.git) Scala · 77 lines

10 import syndor.model.FeedItem

11 import syndor.model.Feed

12 import com.mongodb.casbah.commons.MongoDBObject

13 import java.text.SimpleDateFormat

14

57

58 val title = "Spain, Italy under pressure as EU frames bank deal"

59 val cursor = FeedItem.find(ref = MongoDBObject("title" -> title))

60 val item = cursor.next

61 item.title should be(title)

MaxTimeSpec.scala (git://github.com/mongodb/casbah.git) Scala · 131 lines

49 MongoDBObject("$match" -> ("score" $gte 7)),

50 MongoDBObject("$project" -> MongoDBObject("score" -> 1))

51 ),

52 aggregationOptions

58 "be supported by findAndModify" in {

59 lazy val findAndModify = collection.findAndModify(query = MongoDBObject("_id" -> 1), fields = MongoDBObject(),

60 sort = MongoDBObject(), remove = false, update = MongoDBObject("a" -> 1),

72 "be supported when calling findOne" in {

73 lazy val op = collection.findOne(MongoDBObject.empty, MongoDBObject.empty,

74 MongoDBObject.empty, ReadPreference.Primary,

93

94 "be supported when calling a chained count" in {

95 lazy val op = collection.find().maxTime(oneSecond).count()

96 op should throwA[MongoExecutionTimeoutException]

97 }

MongoService.scala (https://github.com/italia/daf.git) Scala · 177 lines

3 import java.util.Calendar

4

5 import com.mongodb.casbah.commons.MongoDBObject

6 import com.mongodb.{BasicDBObject, ServerAddress}

7 import com.mongodb.casbah.{MongoClient, MongoCredential}

84 }

85

86 def findUserByToken(token:String): Either[String,JsValue] = {

87 findData(USER_COLLECTION_NAME,"token",token)

88 }

89

90 def findAndRemoveUserByToken(token:String): Either[String,JsValue] = {

91 findAndRemoveData(USER_COLLECTION_NAME,"token",token)

92 }

93

94 def findAndRemoveResetPwdByToken(token:String): Either[String,JsValue] = {

95 findAndRemoveData(RESETPWD_COLLECTION_NAME,"token",token)

Db.scala (https://github.com/victorspivak/projects.git) Scala · 58 lines

2

3 import com.mongodb.casbah.{MongoCollection, MongoClient}

4 import com.mongodb.casbah.commons.MongoDBObject

5 import scala.collection.mutable

6 import com.mongodb.{WriteConcern, DBObject}

11 val mongoDb = mongoClient(dbName)

12

13 def deleteCollection(name:String) = collection(name).remove(MongoDBObject.empty)

14 def collection(name:String): MongoCollection = mongoDb(name)

15 }

26 val constrains = new mutable.MutableList[(String, Any)]

27 def filterEquals(key:String, value:Any) = add(key -> value)

28 def filterGT(key:String, value:Any) = add(key -> MongoDBObject("$gt" -> value))

29 def filterLT(key:String, value:Any) = add(key -> MongoDBObject("$lt" -> value))

34 }

35

36 def toDbObject:DBObject = MongoDBObject(constrains.toList)

37 }

38

$resourceName$Dao.scala (https://github.com/ctcarrier/spray-rest-sbt.g8.git) Scala · 63 lines

10 import com.mongodb.{ServerAddress, DBObject}

11 import com.mongodb.casbah.{MongoDB, MongoConnection}

12 import com.mongodb.casbah.commons.MongoDBObject

13 import com.$organization$.$packageName$._

14 import com.$organization$.$packageName$.model._

22 def get$resourceName$(key: ObjectId) = {

23 Future {

24 val q = MongoDBObject("_id" -> key)

25 val dbo = mongoCollection.findOne(q)

38 def update$resourceName$(key: ObjectId, model: $resourceName$) = {

39 Future {

40 val query = MongoDBObject("_id" -> key)

41 val update = \$addToSet("content" -> model)

42

43 mongoCollection.update(query, update, false, false, WriteConcern.Safe)

44

45 val dbo = mongoCollection.findOne(query)

46 dbo.map(f => grater[$resourceName$Wrapper].asObject(f))

47 }

storage.scala (https://github.com/scalaby/oauth.git) Scala · 87 lines

15

16 override def getConsumer(key: String) = {

17 self.consumers.findOne(MongoDBObject("consumerKey" -> key)).map((request) => {

18 Consumer(key, request("consumerSecret").toString)

19 })

23 self.requests.insert(request match {

24 case TokenRequest(consumer, callback, token, tokenSecret) => {

25 MongoDBObject("consumerKey" -> consumer.consumerKey,

26 "callback" -> callback,

27 "token" -> token,

51 }

52 override def get(key: String) = {

53 val p = self.requests.find(MongoDBObject("token" -> key))

54 .sort(MongoDBObject("_id" -> -1)).limit(1)

81

82 override def getNonces(timestamp: String): Set[String] = {

83 nonces.find(MongoDBObject("timestamp" -> timestamp)).map( (resp) => {

84 resp("nonce").toString

85 }).toSet

OpLog.scala (https://github.com/derzzle/casbah.git) Scala · 144 lines

62 def verifyOpLog: BSONTimestamp = {

63 // Verify the oplog exists

64 val last = oplog.find().sort(MongoDBObject("$natural" -> 1)).limit(1)

65 assume(last.hasNext,

66 "No oplog found. mongod must be a --master or belong to a Replica Set.")

72 startTimestamp match {

73 case Some(ts) => {

74 oplog.findOne(MongoDBObject("ts" -> ts)).orElse(

75 throw new Exception("No oplog entry for requested start timestamp."))

76 ts

133 }

134

135 case class MongoUpdateOperation(timestamp: BSONTimestamp, opID: Long, namespace: String, document: MongoDBObject, documentID: MongoDBObject) extends MongoOpLogEntry {

136 val opType = UpdateOp

137 lazy val o2 = documentID

MongoResponseRepository.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 80 lines

5 import com.mongodb.casbah.MongoDB

6 import org.springframework.beans.factory.annotation.Autowired

7 import com.mongodb.casbah.commons.MongoDBObject

8 import org.springframework.stereotype.Repository

9 import com.cyrusinnovation.inquisition.questions.mongodb.MongoQuestionRepository

27

28 def save(questionId: String, response: Response): Response = {

29 questionRepository.findById(questionId) match {

30 case None => {

31 throw new IllegalArgumentException()

59

60 def getResponse(responseId: String): Option[(Question, Response)] = {

61 questionRepository.findResponseQuestion(responseId) match {

62 case Some(x: Question) => {

63 val response = x.responses

Messages.scala (https://github.com/troger/sosmessagedecarte.git) Scala · 114 lines

5 import data._

6 import play.api.mvc._

7 import com.mongodb.casbah.commons.MongoDBObject

8 import com.mongodb.casbah.MongoConnection

9 import org.bson.types.ObjectId

32

33 def index(categoryId: String = "none") = Action { implicit request =>

34 val categoryOrder = MongoDBObject("name" -> 1)

35 val categories = categoriesCollection.find().sort(categoryOrder).foldLeft(List[DBObject]())((l, a) =>

43 }

44

45 val messageOrder = MongoDBObject("createdAt" -> -1)

46 val q = MongoDBObject("categoryId" -> new ObjectId(selectedCategoryId), "state" -> "approved")

68 val rating = messagesCollection.group(MongoDBObject("ratings" -> 1),

69 MongoDBObject("_id" -> message.get("_id")), MongoDBObject("count" -> 0, "total" -> 0), r, f)

70 val j = parse(rating.mkString)

71 message.put("rating", j \ "avg" values)

Libraries.scala (git://github.com/softprops/ls-server.git) Scala · 196 lines

9 import Mongo._

10 import com.mongodb.casbah.commons.Imports.ObjectId

11 import com.mongodb.casbah.commons.{ MongoDBObject => Obj, MongoDBList => ObjList }

12 import com.mongodb.casbah.{ MongoCollection }

13 import com.mongodb.{ BasicDBList, DBObject }

24 libraries { c =>

25 log.info("getting libraries for author %s" format ghuser)

26 f(cct(c.find(

27 $or("ghuser" -> anycase(ghuser), "contributors.login" -> anycase(ghuser))

28 )))

35 libraries { c =>

36 log.info("getting libraries for terms %s" format terms.mkString(", "))

37 val possiblies = (MongoDBObject().empty /: terms)(

38 (a, e) => a += ("name" -> anycase(e))

39 )

Feed.scala (https://github.com/HendraWijaya/syndor.git) Scala · 92 lines

42

43 def grabForFetching: Option[Feed] = {

44 return collection.findAndModify(

45 query = MongoDBObject("fetchStatus.fetching" -> false),

46 fields = MongoDBObject(),

47 sort = MongoDBObject(),

80 private def processSyndEntries(feed: Feed, entries: Seq[SyndEntry]) {

81 entries.foreach { entry =>

82 FeedItem.findOne(MongoDBObject("link" -> entry.getLink)) orElse {

83 FeedItem.insert(FeedItem.make(feed, entry))

84 }

88 def reset() {

89 // Resetting fetching status

90 update(MongoDBObject("fetchStatus.fetching" -> true), $set("fetchStatus.fetching" -> false))

91 }

92 }

SosMessage.scala (https://github.com/troger/sosmessagedecarte.git) Scala · 146 lines

40 val q = MongoDBObject("categoryId" -> new ObjectId(id), "state" -> "approved")

41 val keys = MongoDBObject("category" -> 1, "categoryId" -> 1, "text" -> 1, "createdAt" -> 1)

42 val messages = messagesCollection.find(q, keys).sort(messageOrder).foldLeft(List[JValue]())((l, a) =>

49 val q = MongoDBObject("categoryId" -> new ObjectId(id), "state" -> "approved")

50 val count = messagesCollection.find(q, MongoDBObject("_id")).count

51 val skip = random.nextInt(if (count <= 0) 1 else count)

52

71 val rating = messagesCollection.group(MongoDBObject("ratings" -> 1),

72 MongoDBObject("_id" -> message.get("_id")), MongoDBObject("count" -> 0, "total" -> 0), r, f)

73 val json = messageToJSON(message, Some(parse(rating.mkString)))

74 JsonContent ~> ResponseString(pretty(render(json)))

78

79 case req @ POST(Path(Seg("api" :: "v1" :: "category" :: categoryId :: "message" :: Nil))) =>

80 categoriesCollection.findOne(MongoDBObject("_id" -> new ObjectId(categoryId))).map { category =>

81 val Params(form) = req

82 val text = form("text")(0)

ReminderTest.scala (https://bitbucket.org/ta_jim/lift_userlogin_template.git) Scala · 185 lines

94 User.logUserIn(user, true)

95 Reminder.createReminder(user.id.toString, "Have to play cricket in morning", "03/12/2013")

96 val reminder = Reminder.find(MongoDBObject("description" -> "Have to play cricket in morning"))

97 val validate = Reminder.deleteReminder(reminder.open_!)

98 assert(validate)

110 User.logUserIn(user, true)

111 Reminder.createReminder(user.id.toString, "Have to play cricket in morning", "03/12/2013")

112 val reminder = Reminder.find(MongoDBObject("description" -> "Have to play cricket in morning"))

113 val validate = Reminder.updateReminder(reminder.open_!, "Have to play cricket in morning", "03/12/2013")

114 assert(validate.isRight == true)

122 User.logUserIn(user, true)

123 Reminder.createReminder(user.id.toString, "Have to play cricket in morning", "03/12/2013")

124 val reminder = Reminder.find(MongoDBObject("description" -> "Have to play cricket in morning"))

125 val validate = Reminder.updateReminder(reminder.open_!, "", "03/12/2013")

126 assert(validate.isLeft == true)

ConversionsSpec.scala (https://github.com/derzzle/casbah.git) Scala · 179 lines

92 mongo += MongoDBObject("date" -> jodaDate, "type" -> "joda")

93

94 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "joda"),

95 MongoDBObject("date" -> 1))

118 //mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

119

120 //val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

121 //MongoDBObject("date" -> 1))

136 mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

137

138 val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

139 MongoDBObject("date" -> 1))

149 RegisterJodaTimeConversionHelpers()

150

151 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

152 MongoDBObject("date" -> 1))

User.scala (https://github.com/Bochenski/stackcanon.git) Scala · 246 lines

112 override def allXML = <Users>{super.allXML}</Users>

113

114 def login(username: String, password: String) = findOneBy(MongoDBObject("username" -> username.toLowerCase, "password" -> Codec.hexMD5(password)))

115

116 def findByUsername(username: String) = findOneBy("username", username.toLowerCase)

117

118 def findByGoogleOpenID(id: String) = findOneBy("google_open_id", id)

119

120 def findByFacebookID(id: String) = findOneBy("facebook_id", id)

163

164 def getUsersInRole(role: String) = {

165 findManyByMatchingArrayContent("roles", MongoDBObject(role -> 1))

166 }

167

MongoResponseRepositoryTest.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 113 lines

11 import org.junit.runner.RunWith

12 import org.scalatest.junit.JUnitRunner

13 import com.mongodb.casbah.commons.MongoDBObject

14 import com.mongodb.casbah.commons.MongoDBObject._

24

25 override def beforeEach() {

26 db("questions").remove(MongoDBObject())

27 }

28

36 responseRepository.save(savedQuestion.id.get, response)

37

38 val updatedQuestion = questionRepository.findById(savedQuestion.id.get).get

39 val savedResponse = updatedQuestion.responses.head;

40

49 responseRepository.save(savedQuestion.id.get, new Response(None, "Title", "Creator", "Body"))

50

51 questionRepository.findQuestionCount() should equal(1)

52 }

53

Diagnostic.scala (https://github.com/sshark/resource_manager.git) Scala · 113 lines

48 val id = getRequestAttributes().get("project_id")

49 val configCol = MongoConnection()("vpc")("configuration")

50 val record = MongoDBObject("project_id" -> id)

51 configCol.findOne(record).foreach { rec =>

GroupSpec.scala (https://github.com/derzzle/casbah.git) Scala · 82 lines

37

38 "Work with a normal non-finalized Group statement" in {

39 val cond = MongoDBObject()

40 val key = MongoDBObject("publicationYear" -> 1)

41 val initial = MongoDBObject("count" -> 0)

42 val reduce = "function(obj, prev) { prev.count++ }"

43 val result = mongoDB("books").group(key, cond, initial, reduce)

48 // Test for SCALA-37

49 "Work with a trivial finalized Group statement" in {

50 val cond = MongoDBObject()

51 val key = MongoDBObject("publicationYear" -> 1)

52 val initial = MongoDBObject("count" -> 0)

53 val reduce = "function(obj, prev) { prev.count++ }"

54 val result = mongoDB("books").group(key, cond, initial, reduce, "")

FileStore.scala (https://github.com/delving/dos.git) Scala · 61 lines

36 if (!ObjectId.isValid(id)) return Error("Invalid ID " + id)

37 val oid = new ObjectId(id)

38 val file = fileStore.findOne(oid) getOrElse (return NotFound("Could not find file with ID " + id))

39 new RenderBinary(file.inputStream, file.filename, file.length, file.contentType, false)

40 }

43 // ~~~ public scala API

44

45 @Util def getFilesForItemId(id: ObjectId): List[StoredFile] = fileStore.find(MongoDBObject(ITEM_POINTER_FIELD -> id)).map(fileToStoredFile).toList

46

47 // ~~~ private

50 val id = f.getId.asInstanceOf[ObjectId]

51 val thumbnail = if (FileUpload.isImage(f)) {

52 fileStore.findOne(MongoDBObject(FILE_POINTER_FIELD -> id)) match {

53 case Some(t) => Some(t.id.asInstanceOf[ObjectId])

54 case None => None

Env.scala (https://github.com/kedarbellare/entizer.git) Scala · 159 lines

156 def getMentionIds(query: DBObject = MongoDBObject()) =

157 mentions.find(query, MongoDBObject()).map(_._id.get).toSeq

158 }

159

DAOTest.scala (git://github.com/havocp/mongo-scala-thingy.git) Scala · 80 lines

1 import com.mongodb.casbah.commons.MongoDBObject

2 import com.mongodb.casbah.MongoCollection

3 import com.ometer.bson.Implicits._

18

19 def customQuery[E : Manifest]() = {

20 syncDAO[E].find(BObject("intField" -> 23))

21 }

22 }

30

31 def customQuery[E : Manifest]() = {

32 syncDAO[E].find(BObject("intField" -> 23))

33 }

34 }

40 @org.junit.Before

41 def setup() {

42 MongoUtil.collection("foo").remove(MongoDBObject())

43 MongoUtil.collection("fooWithIntId").remove(MongoDBObject())

casbah_iteration_example.scala (https://github.com/bwmcadams/presentations.git) Scala · 28 lines

1 val mongoColl = MongoConnection()("casbah_test")("test_data")

2 val user1 = MongoDBObject("user" -> "bwmcadams",

3 "email" -> "~~bmcadams~~<AT>novusDOTcom")

4 val user2 = MongoDBObject("user" -> "someOtherUser")

5 mongoColl += user1

6 mongoColl += user2

7 mongoColl.find()

8 // com.novus.casbah.mongodb.MongoCursor =

9 // MongoCursor{Iterator[DBObject] with 2 objects.}

18 ) */

19

20 mongoColl.findOne(q).foreach { x =>

21 // do some work if you found the user...

22 println("Found a user! %s".format(x("user")))

24

25 // Or limit the fields returned

26 val q = MongoDBObject.empty

27 val fields = MongoDBObject("user" -> 1)

MongoUserRepository.scala (https://github.com/cyrusinnovation/inquisition.git) Scala · 74 lines

19 def save(user: SavedUser): SavedUser = {

20 try {

21 users.update(MongoDBObject("_id" -> user.id), grater[User].asDBObject(user.user), false, false, WriteConcern.Safe)

22 } catch {

23 // this is shady since it could also be a username, but we won't let people change that and mongo doesn't seem to tell us, so...there it is

31 val newId = user.username.toLowerCase

32 try {

33 users.insert(MongoDBObject("_id" -> newId) ++ dbObject, WriteConcern.Safe)

34 } catch {

35 case e: DuplicateKey if e.getMessage.contains("_id") => throw new NonUniqueUsernameException(user.username + " is not unique")

44 val query = MongoDBObject("_id" -> lowerCaseId)

45 users.findOne(query) match {

46 case None => None

47 case Some(obj: DBObject) => Some(SavedUser(lowerCaseId, grater[User].asObject(obj)))

55 def findByUsername(username: String) = {

56 users.findOne(MongoDBObject("_id" -> username.toLowerCase)) match {

57 case None => None

58 case Some(obj: DBObject) => Some(dbObj2SavedUser(obj))

Reminder.scala (https://bitbucket.org/ta_jim/lift_userlogin_template.git) Scala · 120 lines

14 import org.bson.types.ObjectId

15 import java.text.ParsePosition

16 import com.mongodb.casbah.commons.MongoDBObject

17

18 class Reminder extends MongoRecord[Reminder] with ObjectIdPk[Reminder] with Loggable {

61 }

62

63 def findAllNotes(userId: String) = Reminder.findAll((("owner" -> userId)))

64

65 def findAllNotes(userId: String, sortOrder: Int, limit: Int, skip: Int) =

115 val start_date = new Date(new Date().getYear(), new Date().getMonth(), new Date().getDate())

116 val end_date = new Date(new Date().getYear(), new Date().getMonth(), new Date().getDate() + 1)

117 Reminder.findAll(MongoDBObject("dob" -> MongoDBObject("$gte" -> start_date, "$lt" -> end_date), "owner" -> new ObjectId(userID)))

118 }

119 }

MapReduceCommand.scala (git://github.com/ymasory/scala-corpus.git) Scala · 154 lines

100

101 def toDBObj = {

102 val dataObj = MongoDBObject.newBuilder

103 collection match {

104 case "" => throw new MapReduceError("collection must be defined.")

SlugMapping.scala (https://gitlab.com/guodman/webcbv) Scala · 67 lines

13

14 def save = {

15 var builder = MongoDBObject.newBuilder

16 builder += "_id" -> _id

17 builder += "path" -> path

42

43 def getByKey(key: String): SlugMapping = {

44 val r = dbCollection.findOne(MongoDBObject("key" -> key))

45 return r.map(factory).orNull

46 }

47

48 def getByPath(path: String): SlugMapping = {

49 val r = dbCollection.findOne(MongoDBObject("path" -> path))

50 return r.map(factory).orNull

51 }

Categories.scala (https://github.com/troger/sosmessagedecarte.git) Scala · 57 lines

4 import data._

5 import play.api.mvc._

6 import com.mongodb.casbah.commons.MongoDBObject

7 import com.mongodb.casbah.MongoConnection

8 import org.bson.types.ObjectId

24

25 def index = Action { implicit request =>

26 val categoryOrder = MongoDBObject("name" -> 1)

27 val categories = categoriesCollection.find().sort(categoryOrder).foldLeft(List[DBObject]())((l, a) =>

38 },

39 v => {

40 val builder = MongoDBObject.newBuilder

41 builder += "name" -> v

42 builder += "createdAt" -> new Date()

50 def delete (id: String) = Action { implicit request =>

51 val oid = new ObjectId(id)

52 val o = MongoDBObject("_id" -> oid)

53 categoriesCollection.remove(o)

54 Redirect(routes.Categories.index).flashing("actionDone" -> "categoryDeleted")

CoreWrappersSpec.scala (https://github.com/derzzle/casbah.git) Scala · 167 lines

114 coll.insert(MongoDBObject("foo" -> "bar"))

115 val basicFind = coll.find(MongoDBObject("foo" -> "bar"))

116

117 basicFind must haveSize(1)

121 findOne must beSome

122

123 val findOneMatch = coll.findOne(MongoDBObject("foo" -> "bar"))

124

125 findOneMatch must beSome

151

152 "Chain operations must return the proper *subtype*" in {

153 val cur = coll.find(MongoDBObject("foo" -> "bar")) skip 5

154 cur must beAnInstanceOf[MongoCursor]

155

156 val cur2 = coll.find(MongoDBObject("foo" -> "bar")) limit 25 skip 12

157 cur2 must beAnInstanceOf[MongoCursor]

158

MetadataCache.scala (https://github.com/delving/culture-hub.git) Scala · 124 lines

75 val schemaVersions = item.schemaVersions.foldLeft(MongoDBObject()) { (r, c) => r + (c._1 -> c._2) }

76 update(

77 q = MongoDBObject("collection" -> item.collection, "itemType" -> item.itemType, "itemId" -> item.itemId),

78 o = $set(

79 "modified" -> new Date(),

101 }

102

103 val cursor = find(q).sort(MongoDBObject("index" -> 1))

104 if (limit.isDefined) {

105 cursor.limit(limit.get)

117 def findOne(itemId: String): Option[MetadataItem] = findOne(MongoDBObject("collection" -> col, "itemType" -> itemType, "itemId" -> itemId))

118

119 def findMany(itemIds: Seq[String]): Seq[MetadataItem] = find(MongoDBObject("collection" -> col, "itemType" -> itemType) ++ ("itemId" $in itemIds)).toSeq

120

121 def remove(itemId: String) { remove(MongoDBObject("collection" -> col, "itemId" -> itemId)) }

$actor_name$.scala (https://github.com/itam/scala_akka_mongo.g8.git) Scala · 43 lines

3 import akka.dispatch.Dispatchers

4 import com.mongodb.casbah.Imports._

5 import com.mongodb.casbah.commons.MongoDBObject

6 import akka.actor.Actor._

7 import akka.routing._

31 case "post" => {

32 println("POSTing some random text.")

33 collection.insert(MongoDBObject("randomText" -> "POSTING some random text"))

34 }

35 case f: Fetch[ObjectId] => {

36 val dbo = collection.findOne(MongoDBObject("_id" -> f.value))

37

38 self.channel ! grater[$model_name$].asObject(dbo.get)

FeedUpdaterSpec.scala (https://github.com/HendraWijaya/syndor.git) Scala · 139 lines

56 FeedItem.collection.count should be(10)

57

58 verifyFeedItems(FeedItem.find(MongoDBObject()).sort(orderBy = MongoDBObject("publishedDate" -> -1)))

59

60 Feed.findOneByID(feed.id) map { updatedFeed =>

67 updatedFeed.fetchStatus.fetchStart should be < updatedFeed.fetchStatus.fetchEnd

68 } orElse {

69 fail("Unable to find updated feed with id %s".format(feed.id))

70 }

71

111 FeedItem.collection.count should be(0)

112

113 Feed.findOneByID(feed.id) map { updatedFeed =>

114 updatedFeed.fetchStatus.fetching should be(false)

115 updatedFeed.fetchStatus.success should be(false)

CasbahDemo.scala (https://github.com/jlcheng/hello-finagle.git) Scala · 45 lines

1 package org.jcheng

2 import com.mongodb.casbah.MongoConnection

3 import com.mongodb.casbah.commons.MongoDBObject

4 import com.mongodb.casbah.commons.conversions._

5

17 println("Assuming this is not the first run...")

18 println("Size should be 2: " + testData.size)

19 testData.remove(MongoDBObject("name" -> "firs"))

20 println("Size should be 1: " + testData.size)

21 testData.remove(MongoDBObject()) // remove everything

29 testData += objA

30

31 testData.findOne(MongoDBObject("name" -> "third"), MongoDBObject("val"->1)).foreach { x =>

32 println(x)

33 }

MongoAllOrOneAccess.scala (https://github.com/jmrowe/PartsDbWebApp.git) Scala · 53 lines

23 * Define a function that generates a query to get a specific item from the db

24 */

25 private val queryOne: (String, Identifier) => MongoDBObject = (idFieldName: String, idFieldValue: Identifier) => {

26 val mongoIdentifier = MongoDBObject("id" -> idFieldValue.id)

27 MongoDBObject(idFieldName -> mongoIdentifier)

28 }

29

36

37 def getOne[T <: AnyRef](idFieldName: String, id: Identifier)(implicit mf: Manifest[T]): Option[T] = {

38 collection.findOne(queryOne(idFieldName, id)).toList match {

39 case Nil => None

40 case head :: Nil => Some(convertFromMongoDbObject(head))

41 case head :: tail :: Nil => {

42 error("Query for single item [%s] returned multiple objects. Returning first result only")

43 Some(convertFromMongoDbObject(head))

44 }

45 }

Role.scala (https://github.com/Bochenski/stackcanon.git) Scala · 77 lines

32

33 def create(name: String) = {

34 val builder = MongoDBObject.newBuilder

35 builder += "name" -> name

36 val newObj = builder.result().asDBObject

40

41 def destroy(id: String) = {

42 remove(MongoDBObject("_id" -> new ObjectId(id)))

43 }

44

47 }

48

49 def findByName(name: String) = {

50 findOneBy("name", name)

64

65 private def CreateRoleIfMissing(role: String) = {

66 findByName(role) match {

67 case None => {

68 create(role)

RegionInfoMongoHelper.scala (https://github.com/goodrain/realtime-message-system.git) Scala · 153 lines

8 import com.mongodb.casbah.MongoDB

9 import scala.util.Try

10 import com.mongodb.casbah.commons.MongoDBObject

11 import java.util.ArrayList

12 import com.mongodb.DBObject

46 try {

47 val collection = mongoDb(dbname)(collectionName)

48 var cursor = collection.find()

49 while (cursor.hasNext) {

50 result.add(cursor.next)

118 try {

119 val collection = mongoDb(dbname)(collectionName)

120 var cursor = collection.find()

121 while (cursor.hasNext) {

122 result.add(cursor.next)

ThumbnailDeletionProcessor.scala (https://github.com/delving/dos.git) Scala · 49 lines

22 import controllers.dos.Thumbnail

23 import org.bson.types.ObjectId

24 import com.mongodb.casbah.commons.MongoDBObject

25

26 /**

35 } else {

36 info(task, "Starting to delete thumbnails for directory " + task.path)

37 val thumbs = fileStore.find(MongoDBObject(ORIGIN_PATH_FIELD -> task.path.r, COLLECTION_IDENTIFIER_FIELD -> task.params(COLLECTION_IDENTIFIER_FIELD).toString, ORGANIZATION_IDENTIFIER_FIELD -> task.params(ORGANIZATION_IDENTIFIER_FIELD).toString))

38 Task.setTotalItems(task, thumbs.size)

39 thumbs foreach {

MaxLengthsProcessor.scala (https://github.com/kedarbellare/entizer.git) Scala · 63 lines

10 class MaxLengthsProcessor(val inputColl: MongoCollection,

11 val useOracle: Boolean = false) extends ParallelCollectionProcessor {

12 def name = "maxLengthFinder[oracle=" + useOracle + "]"

13

14 def inputJob = {

16 JobCenter.Job(select = MongoDBObject("isRecord" -> 1, "bioLabels" -> 1))

17 else

18 JobCenter.Job(query = MongoDBObject("isRecord" -> true), select = MongoDBObject("isRecord" -> 1, "bioLabels" -> 1))

19 }

20

48 def name = "uniqueClusters"

49

50 def inputJob = JobCenter.Job(select = MongoDBObject("cluster" -> 1))

51

52 override def newOutputParams(isMaster: Boolean = false) = new HashSet[String]

MongoWriter.scala (https://github.com/tackley/travel-map.git) Scala · 27 lines

2

3 import com.mongodb.casbah.Imports._

4 import com.mongodb.casbah.commons.MongoDBObject

5 import org.joda.time.DateTime

6 import com.weiglewilczek.slf4s.Logging

13

14 def mostRecentLastModified = {

15 ContentItem.find(MongoDBObject())

16 .sort(orderBy = MongoDBObject("lastModified" -> -1))

Implicits.scala (https://github.com/derzzle/casbah.git) Scala · 110 lines

47 * @return DBObject

48 */

49 def asDBObject = map2MongoDBObject(map)

50 }

51

52 implicit def map2MongoDBObject(map: scala.collection.Map[String, Any]): DBObject = MongoDBObject(map.toList)

53

54 // implicit def iterable2DBObject(iter: Iterable[(String, Any)]): DBObject = MongoDBObject(iter.toList)

76

77 trait BaseImports {

78 val MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

79 val DBObject = MongoDBObject

83

84 trait TypeImports {

85 type MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

86 type MongoDBList = com.mongodb.casbah.commons.MongoDBList

87 type DBObject = com.mongodb.DBObject

MuddlApp.scala (https://github.com/jorgeortiz85/muddl-sample.git) Scala · 36 lines

20 // There's weird data in the staging venue db with empty venues

21 // which blow up on deserialization, so we'll avoid them

22 val nonEmptyVenues = MongoDBObject("userid" -> MongoDBObject("$exists" -> true))

23

24 val venues: Seq[NiceVenue] = databases.venues.find(nonEmptyVenues, 10)

25 val checkins: Seq[Checkin] = databases.checkins.find(MongoDBObject(), 10)

26

27 val venue = venues(0)

Medicine.scala (https://github.com/gertjana/Medicate.git) Scala · 61 lines

42

43 def getById(id:String):Option[MedicineObject] = {

44 MedicineDAO.find(MongoDBObject("_id" -> new ObjectId(id)))

45 .limit(1)

46 .toList

49

50 def getByNr(nr:Int):Option[MedicineObject] = {

51 MedicineDAO.find(MongoDBObject("nr" -> nr))

52 .limit(1)

53 .toList

57

58 def list():List[MedicineObject] = {

59 MedicineDAO.find(MongoDBObject()).toList

60 }

61 }

BulkWriteOperationSpec.scala (git://github.com/mongodb/casbah.git) Scala · 406 lines

292 collection.findOne(MongoDBObject("_id" -> 7)) must beSome(MongoDBObject("_id" -> 7))

293 collection.findOne(MongoDBObject("_id" -> 8)) must beSome(MongoDBObject("_id" -> 8))

294 }

295

335 collection.findOne(MongoDBObject("_id" -> 1)) must beSome(MongoDBObject("_id" -> 1, "x" -> 2))

336 collection.findOne(MongoDBObject("_id" -> 2)) must beSome(MongoDBObject("_id" -> 2, "x" -> 3))

337 collection.findOne(MongoDBObject("_id" -> 3)) must beNone

341 collection.findOne(MongoDBObject("_id" -> 7)) must beSome(MongoDBObject("_id" -> 7))

342 collection.findOne(MongoDBObject("_id" -> 8)) must beSome(MongoDBObject("_id" -> 8))

343 }

344

350 operation.insert(MongoDBObject("_id" -> 1))

351 operation.find(MongoDBObject("_id" -> 2)).updateOne(MongoDBObject("$set" -> MongoDBObject("x" -> 3)))

352 operation.insert(MongoDBObject("_id" -> 3))

401 operation.find(MongoDBObject("_id" -> 5)).replaceOne(MongoDBObject("_id" -> 5, "x" -> 4))

402 operation.find(MongoDBObject("_id" -> 6)).replaceOne(MongoDBObject("_id" -> 6, "x" -> 5))

403 operation.insert(MongoDBObject("_id" -> 7))

Moderation.scala (https://github.com/troger/sosmessagedecarte.git) Scala · 69 lines

4 import play.api.mvc._

5 import play.api.data._

6 import com.mongodb.casbah.commons.MongoDBObject

7 import com.mongodb.casbah.MongoConnection

8 import org.bson.types.ObjectId

31 def approve(messageId: String, selectedTab: String) = Action { implicit request =>

32 val oid = new ObjectId(messageId)

33 var o = messagesCollection.findOne(MongoDBObject("_id" -> oid)).get

34 o += ("state" -> "approved")

35 messagesCollection.save(o)

39 def reject(messageId: String, selectedTab: String) = Action { implicit request =>

40 val oid = new ObjectId(messageId)

41 var o = messagesCollection.findOne(MongoDBObject("_id" -> oid)).get

42 o += ("state" -> "rejected")

43 messagesCollection.save(o)

Loader.scala (https://github.com/tackley/apache-log-uploader.git) Scala · 36 lines

1 import com.mongodb.casbah.commons.MongoDBObject

2 import com.mongodb.casbah.MongoConnection

3 import io.Source

11 if (args.isEmpty) {

12 for {

13 obj <- coll.find().sort(MongoDBObject("ms" -> -1)).limit(200)

14 url <- Option(obj.get("url")).map(_.toString)

15 ms <- Option(obj.get("ms")).map(_.toString.toInt)

Db.scala (https://github.com/victorspivak/projects.git) Scala · 58 lines

2 //

3 //import com.mongodb.casbah.{MongoCollection, MongoClient}

4 //import com.mongodb.casbah.commons.MongoDBObject

5 //import scala.collection.mutable

6 //import com.mongodb.{WriteConcern, DBObject}

11 // val mongoDb = mongoClient(dbName)

12 //

13 // def deleteCollection(name:String) = collection(name).remove(MongoDBObject.empty)

14 // def collection(name:String): MongoCollection = mongoDb(name)

15 //}

26 // val constrains = new mutable.MutableList[(String, Any)]

27 // def filterEquals(key:String, value:Any) = add(key -> value)

28 // def filterGT(key:String, value:Any) = add(key -> MongoDBObject("$gt" -> value))

29 // def filterLT(key:String, value:Any) = add(key -> MongoDBObject("$lt" -> value))

34 // }

35 //

36 // def toDbObject:DBObject = MongoDBObject(constrains.toList)

37 //}

38 //

MapReduceCommand.scala (https://github.com/derzzle/casbah.git) Scala · 157 lines

96

97 def toDBObject = {

98 val dataObj = MongoDBObject.newBuilder

99 input match {

100 case "" => throw new MapReduceException("input must be defined.")

119 dataObj += "out" -> (output match {

120 case MapReduceStandardOutput(coll: String) => coll

121 case MapReduceMergeOutput(coll: String) => MongoDBObject("merge" -> coll)

122 case MapReduceReduceOutput(coll: String) => MongoDBObject("reduce" -> coll)

123 case MapReduceInlineOutput => MongoDBObject("inline" -> true)

124 case other => throw new IllegalArgumentException("Invalid Output Type '%s'".format(other))

125 })

Logs.scala (https://github.com/delving/dos.git) Scala · 56 lines

22 import org.bson.types.ObjectId

23 import play.mvc.results.Result

24 import com.mongodb.casbah.commons.MongoDBObject

25 import com.novus.salat.dao.SalatMongoCursor

26

33

34 def list(taskId: ObjectId, lastCount: Int): Result = {

35 val cursor: SalatMongoCursor[Log] = Log.find(MongoDBObject("task_id" -> taskId)).sort(MongoDBObject("date" -> 1))

36 val (logs, skipped) = if(lastCount != null && lastCount > 0) {

37 if(cursor.count - lastCount > 100) {

51

52 def view(taskId: ObjectId): Result = {

53 val cursor: SalatMongoCursor[Log] = Log.find(MongoDBObject("task_id" -> taskId)).sort(MongoDBObject("date" -> 1))

54 Text(cursor.map(log => log.date + "\t" + log.level.name.toUpperCase + "\t" + log.node + "\t" + log.message).mkString("\n"))

55 }

MongoLoader.scala (https://github.com/chrislewis/hazelbox.git) Scala · 56 lines

26

27 def load(key: ObjectId) = {

28 val one = collection.findOne(MongoDBObject("_id" -> key))

29 one.map(grater[Person].asObject(_)).getOrElse(null) // java, ftl

30 }

39

40 def delete(key: ObjectId) {

41 collection.remove(MongoDBObject("_id" -> key))

42 }

43

MongoIdentifierAccess.scala (https://github.com/jmrowe/PartsDbWebApp.git) Scala · 46 lines

16

17 private val incrementUniqueId = (currentId: Long) => {

18 val newIdObject = MongoDBObject("uniqueId" -> (currentId + 1))

19 val findIdObjectQuery = "uniqueId" $exists true

20 collection.findOne(findIdObjectQuery) match {

21 case None => collection += newIdObject

22 case _ => collection.findAndModify(findIdObjectQuery, newIdObject)

32 */

33 def nextId(): Long = {

34 val findOneQuery = collection.findOne(idQuery)

35 val idValue = findOneQuery match {

Implicits.scala (https://github.com/d5nguyenvan/casbah.git) Scala · 110 lines

47 * @return DBObject

48 */

49 def asDBObject = map2MongoDBObject(map)

50 }

51

52 implicit def map2MongoDBObject(map: scala.collection.Map[String, Any]): DBObject = new BasicDBObject(map.asJava)

53

54 implicit def wrapDBObj(in: DBObject): MongoDBObject =

76

77 trait BaseImports {

78 val MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

79 val DBObject = MongoDBObject

83

84 trait TypeImports {

85 type MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

86 type MongoDBList = com.mongodb.casbah.commons.MongoDBList

87 type DBObject = com.mongodb.DBObject

FileUpload.scala (https://github.com/delving/dos.git) Scala · 165 lines

54 toDelete =>

55 // remove thumbnails

56 fileStore.find(MongoDBObject(FILE_POINTER_FIELD -> oid)) foreach {

57 t =>

58 fileStore.remove(t.getId.asInstanceOf[ObjectId])

67 // ~~ public Scala API

68

69 @Util def getFilesForUID(uid: String): Seq[StoredFile] = fileStore.find(MongoDBObject(UPLOAD_UID_FIELD -> uid)) map {

70 f => {

71 val id = f.getId.asInstanceOf[ObjectId]

72 val thumbnail = if (isImage(f)) {

73 fileStore.findOne(MongoDBObject(FILE_POINTER_FIELD -> id)) match {

74 case Some(t) => Some(t.id.asInstanceOf[ObjectId])

75 case None => None

test.scala (git://github.com/ochafik/Scalaxy.git) Scala · 91 lines

80

81 val dict = MongoConnection("localhost")("appdb")("dict")

82 val index = MongoDBObject("_id" -> "_index")

83 dict.update(index, makeEntry("applaud"), true, false)

84 dict.update(index, makeEntry("apple"), true, false)

86 dict.update(index, makeEntry("banana"), true, false)

87

88 val entry = dict.findOne(index ++ ("a.p.p" $exists true))

89 println(entry)

90 }

KmlGenerator.scala (https://github.com/tackley/travel-map.git) Scala · 41 lines

2

3 import loader.ContentItem

4 import com.mongodb.casbah.commons.MongoDBObject

5 import xml.{NodeSeq, Unparsed}

6

16 {

17 for {

18 c <- ContentItem.find(MongoDBObject())

19 lat <- c.lat

20 long <- c.long

DefRepo.scala (git://github.com/ornicar/scalex.git) Scala · 32 lines

15

16 def byIds(ids: Seq[String]): List[Def] = {

17 val defs = find("_id" $in ids) toList

18 val sorted = ids map { id => defs.find(_.id == id) }

21

22 def removePack(pack: String) {

23 collection remove MongoDBObject("pack" -> pack)

24 }

25

26 def findAll: List[Def] = find(MongoDBObject()).toList

27

28 def findByDeclaration(dec: String) = findOne(MongoDBObject(

Implicits.scala (https://github.com/ymasory/scala-corpus.git) Scala · 111 lines

47 * @return DBObject

48 */

49 def asDBObject = map2MongoDBObject(map)

50 }

51

52 implicit def map2MongoDBObject(map: scala.collection.Map[String, Any]): DBObject = new BasicDBObject(map.asJava)

53

54

77

78 trait BaseImports {

79 val MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

80 val DBObject = MongoDBObject

84

85 trait TypeImports {

86 type MongoDBObject = com.mongodb.casbah.commons.MongoDBObject

87 type MongoDBList = com.mongodb.casbah.commons.MongoDBList

88 type DBObject = com.mongodb.DBObject

MongoContentItemStore.scala (https://github.com/rhyskeepence/guardian-travelbook.git) Scala · 89 lines

1 package rhyskeepence.loader

2

3 import com.mongodb.casbah.commons.MongoDBObject

4 import org.joda.time.DateTime

5 import rhyskeepence.MongoStorage

20

21 def write(item: ContentItem) = {

22 val contentItemBuilder = MongoDBObject.newBuilder

23 contentItemBuilder += "_id" -> item.id

24 contentItemBuilder += "headline" -> item.headline

30 item.geolocation.foreach {

31 loc =>

32 val geolocation = MongoDBObject.newBuilder

33 geolocation += "lat" -> loc.lat

34 geolocation += "lon" -> loc.lon

ApplicationSetting.scala (https://github.com/Bochenski/stackcanon.git) Scala · 77 lines

21 </ApplicationSetting>

22

23 def findByKey(key: String) = findOneBy("key", key)

24

25 def create(key: String, value: String): Boolean = {

27 Logger.info("in model create appplication setting")

28 //check whether the user exists

29 val setting = findByKey(key)

30 setting match {

31 case Some(_) => false

32 case None => {

33 val builder = MongoDBObject.newBuilder

34 builder += "key" -> key

35 builder += "value" -> value

User.scala (https://github.com/dbongo/play-mongo-securesocial.g8.git) Scala · 45 lines

27 val dao = new SalatDAO[User, UserId](collection = mongoCollection("users")) {}

28

29 def findOneBySocialId(socialId:UserId):Option[User] = dao.findOne(MongoDBObject("_id._id" -> socialId.id, "_id.providerId" -> socialId.providerId))

30 def findOneByEmailAndProvider(email: String, providerId:String): Option[User] = dao.findOne(MongoDBObject("email" -> email, "authMethod.method" -> providerId))

35 val dao = new SalatDAO[Token, String](collection = mongoCollection("tokens")) {}

36

37 def findToken(uuid:String):Option[Token] = dao.findOne(MongoDBObject("uuid" -> uuid))

38 def deleteExpiredTokens() {

39 val now = new _root_.java.util.Date()

40 dao.find("expirationTime" \$lte now).foreach(

41 TokenDAO.remove(_)

42 )

FileManager.scala (https://github.com/Bochenski/stackcanon.git) Scala · 75 lines

27 fh.filename = image.getName()

28 fh.contentType = "image/" + extension.get.toString

29 fh.metaData = MongoDBObject("parentType" -> parentType, "parentId" -> parentId, "sequence" -> sequence)

30 }

31 parentType + "/" + parentId + "/image/"+ sequence.toInt

51

52 def getFile(parentType: String, parentId: String, sequence: Int): Option[GridFSDBFile] = {

53 MongoDB.getGridFS.findOne(MongoDBObject("metadata.parentType" -> parentType, "metadata.parentId" -> parentId, "metadata.sequence" -> sequence))

54 }

55

56 def getFileCount(parentType: String, parentId: String) = {

57 val count = MongoDB.getDB("fs.files").count(MongoDBObject("metadata.parentType" -> parentType, "metadata.parentId" -> parentId))

58 Logger.info("found " + count.toString + " files")

59 count

6fece33916d5900c7271d9e97e65fea980a85173BasicMongoTest.scala (https://github.com/aliostad/deep-learning-lang-detection.git) Scala · 65 lines

42

43 scenario("an entry with a unique field is queried from the database") {

44 val foundItems = mongoDB.find(MongoDBObject("x" -> "y"))

45 assert(foundItems.length === 1)

46 }

47

48 scenario("multiple entries with common fields are queried from the database") {

49 val foundItems = mongoDB.find(MongoDBObject("pie" -> 3.14))

50 assert(foundItems.length === 2)

51 }

53 scenario("one entry is removed from the database") {

54 val oldLength = mongoDB.size

55 for (entry <- mongoDB.find(MongoDBObject("x" -> "y")))

56 mongoDB -= entry

57 assert(mongoDB.size === oldLength - 1)

ReadResource.scala (http://sample-scala.googlecode.com/svn/trunk/) Scala · 48 lines

3 import org.scalatra.ScalatraServlet

4 import org.steve.utils.CommonConversions._

5 import com.mongodb.casbah.commons.MongoDBObject

6

7 class SampleResource extends ScalatraServlet {

8

9 get("/") {

10 val names = PersonDAO.find(MongoDBObject()) map { _.name }

11 <html>

12 <ul>

25 contentType = "application/json"

26 val id = params("id")

27 PersonDAO.findOneByID(id.toObjectId).toJson

28 }

29

DataSetEventLog.scala (https://github.com/delving/culture-hub.git) Scala · 52 lines

25

26 def initIndexes(collection: MongoCollection) {

27 addIndexes(collection, Seq(MongoDBObject("orgId" -> 1)))

28 addIndexes(collection, Seq(MongoDBObject("transientEvent" -> 1)))

36 def findRecent = {

37 val nonTransient = find(MongoDBObject("transientEvent" -> false)).limit(10).sort(MongoDBObject("_id" -> -1)).toList

38 val transient = find(MongoDBObject("transientEvent" -> true)).limit(40).sort(MongoDBObject("_id" -> -1)).toList

42

43 def removeTransient() {

44 val recent = find(MongoDBObject("transientEvent" -> true)).limit(10).sort(MongoDBObject("_id" -> -1)).toList.reverse.headOption

45 recent.map { r =>

46 remove(MongoDBObject("transientEvent" -> true) ++ ("_id" $lt r._id))

47 }.getOrElse {

48 remove(MongoDBObject("transientEvent" -> true))

49 }

50 }

MapReduceCommand.scala (git://github.com/mongodb/casbah.git) Scala · 136 lines ✨ Summary

This Scala code defines a MapReduceCommand class that represents a MongoDB map-reduce operation. It allows users to specify input, map and reduce functions, output location, query, sort, limit, finalize function, JavaScript scope, and verbosity level. The class generates a DBObject representation of the command, which can be used to execute the map-reduce operation on a MongoDB database.

70

71 def toDBObject: DBObject = {

72 val dataObj = MongoDBObject.newBuilder

73 input match {

74 case "" => throw new MapReduceException("input must be defined.")

93 dataObj += "out" -> (output match {

94 case MapReduceStandardOutput(coll: String) => coll

95 case MapReduceMergeOutput(coll: String) => MongoDBObject("merge" -> coll)

96 case MapReduceReduceOutput(coll: String) => MongoDBObject("reduce" -> coll)

97 case MapReduceInlineOutput => MongoDBObject("inline" -> true)

98 case other => throw new IllegalArgumentException("Invalid Output Type '%s'".format(other))

99 })

ShapefileWriter.scala (https://github.com/foursquare/fsqio.git) Scala · 107 lines

74 // val collection = new ListFeatureCollection(TYPE)

75

76 // val total = MongoGeocodeDAO.count(MongoDBObject("hasPoly" -> true))

77

78 // val records =

79 // MongoGeocodeDAO.find(MongoDBObject("hasPoly" -> true))

80

81 // val geomFactory = new GeometryFactory()

GroupSpec.scala (git://github.com/mongodb/casbah.git) Scala · 93 lines ✨ Summary

This Scala code defines a test specification for MongoDB’s Group interface, testing its functionality with various group statements and verifying the results against expected values. It uses the Casbah library to interact with a MongoDB database, importing data from a JSON file and performing operations such as grouping and counting documents. The tests ensure that the Group interface behaves correctly under different scenarios.

36

37 "Work with a normal non-finalized Group statement" in new testData {

38 val cond = MongoDBObject()

39 val key = MongoDBObject("publicationYear" -> 1)

40 val initial = MongoDBObject("count" -> 0)

41 val reduce = "function(obj, prev) { prev.count++ }"

42

47 // Test for CASBAH-37

48 "Work with a trivial finalized Group statement" in new testData {

49 val cond = MongoDBObject()

50 val key = MongoDBObject("publicationYear" -> 1)

51 val initial = MongoDBObject("count" -> 0)

52 val reduce = "function(obj, prev) { prev.count++ }"

53

MongoTest.scala (git://github.com/btarbox/Log4ScalaFugue.git) Scala · 69 lines

43 removeOldData(mongo)

44 loadSomeData(mongo)

45 find(mongo)

46 }

47

48 def removeOldData(mongo: MongoDataGetter) = {

49 for ( x <- mongo.conn.find()) {

50 mongo.conn.remove(x)

51 }

54 def loadSomeData(mongo: MongoDataGetter) = {

55 for(x <- 1 to 20) {

56 val newObj = MongoDBObject("timestamp" -> x.toString,

57 "category" -> "general",

58 "msg" -> "bla bla bla")

63 def find(mongo: MongoDataGetter) = {

64 for { x <- mongo.conn.find().sort(MongoDBObject("timeColumn" -> "1")); thisTime = x.get("timestamp"); if(thisTime != null)} {

65 println(x)

66 println(thisTime)

Version.scala (https://github.com/Bochenski/stackcanon.git) Scala · 119 lines

25

26 def create(version: Int) = {

27 val builder = MongoDBObject.newBuilder

28 builder += "version" -> version

29 val newObj = builder.result().asDBObject

33

34 def check() = {

35 //first find our current DB version

36 Logger.info("checking DB version and updating if required)")

37 val appVersion = Play.configuration.getProperty("version").toInt

38 Logger.info("appVersion " + appVersion.toString)

39 findOne match {

40 case Some(entry) => {

41

FieldCollection.scala (https://github.com/kedarbellare/entizer.git) Scala · 95 lines

71 def getRecordClusters = {

72 val rnd = new Random

73 val allValues = entityColl.find(MongoDBObject(), MongoDBObject()).map(dbo => FieldValue(this, Some(dbo._id.get))).toSeq

74 ccPivot(rnd, allValues)

75 }

OnePortfolio00.scala (http://scaly.googlecode.com/svn/trunk/) Scala · 96 lines

35 import com.mongodb.casbah.MongoCursor

36 import com.mongodb.casbah.MongoConnection

37 import com.mongodb.casbah.commons.MongoDBObject

38 import com.mongodb.BasicDBList

39 import com.mongodb.BasicDBObject

56 val portfsCollecton = mongo("Portfolios")

57

58 val portfsQuery = MongoDBObject("id" -> 1)

59

60 val portfsCursor : MongoCursor = portfsCollecton.find(portfsQuery)

67

68 val value = bondIds.foldLeft(0.0) { (sum, id) =>

69 val bondsQuery = MongoDBObject("id" -> id)

70

71 val bondsCursor: MongoCursor = bondsCollection.find(bondsQuery)

ArchiveRepository.scala (https://github.com/kufi/Filefarmer.git) Scala · 64 lines

2 import com.google.inject.Inject

3 import ch.filefarmer.database.connection.IConnection

4 import com.mongodb.casbah.commons.MongoDBObject

5 import ch.filefarmer.poso._

6 import com.mongodb.casbah.Implicits._

13

14 def getArchive(identity:String) = {

15 val search = MongoDBObject("identity" -> identity)

16

17 archiveConnection.findOne(search) match {

45

46 def getArchiveTree(parent:String = ""): Option[ArchiveTree] = {

47 var search = MongoDBObject("parentArchiveId" -> parent)

48

49 val tree = new ArchiveTree()

Article.scala (https://github.com/ngocdaothanh/tivua.git) Scala · 125 lines

59 val numPages = (count / ITEMS_PER_PAGE) + (if (count % ITEMS_PER_PAGE == 0) 0 else 1)

60

61 val cur = articleColl.find().sort(MongoDBObject("sticky" -> -1, "thread_updated_at" -> -1)).skip((p - 1) * ITEMS_PER_PAGE).limit(ITEMS_PER_PAGE)

62 val buffer = ArrayBuffer[Article]()

63 for (o <- cur) {

87 val numPages = (count / ITEMS_PER_PAGE) + (if (count % ITEMS_PER_PAGE == 0) 0 else 1)

88

89 val cur = articleCategoryColl.find(MongoDBObject("category_id" -> categoryId)).sort(MongoDBObject("sticky" -> -1, "thread_updated_at" -> -1)).skip((page - 1) * ITEMS_PER_PAGE).limit(ITEMS_PER_PAGE)

90 val buffer = ArrayBuffer[Article]()

91 for (o <- cur) {

112

113 val categories = {

114 val cur = articleCategoryColl.find(MongoDBObject("article_id" -> id))

115 val buffer = ArrayBuffer[Category]()

116 for (o <- cur) {

SalatExamples.scala (https://bitbucket.org/Tolsi/scala-school-2018-2.git) Scala · 39 lines

17 val entity: Option[Entity] = dao.findOneById("333")

18

19 val queryResult: SalatMongoCursor[Entity] = dao.find(MongoDBObject("params.x" -> 15))

20

21 val res: List[Entity] = queryResult.toList

31 val removeByIdResult = dao.removeById("4")

32

33 val removeByQueryResult = dao.remove(MongoDBObject("_id" -> "5"))

34

35 val removeEntityResult = dao.remove(Entity("6", Param(6, List.empty)))

36

37 val updateResult: WriteResult = dao.update(MongoDBObject("_id" -> "4"), $set("params.x" -> 18), upsert = false)

38

39 }

MovieActor.scala (https://bitbucket.org/tdrobinson/traktor.git) Scala · 87 lines

8 import com.mongodb.casbah.Implicits._

9 import org.bson.types.ObjectId

10 import com.mongodb.casbah.commons.MongoDBObject

11

12 import scala.concurrent.Future

34

35 def listAll(implicit dbObject2JObject: DBObject => JValue) =

36 JArray(collection.find().toList.map(db => dbObject2JObject(db)))

37

38 def listAllPending(implicit dbObject2JObject: DBObject => JValue) =

67 try

68 {

69 val forRemoval = ms.map(m => collection.findOne(MongoDBObject("filename" -> m))).filter(m => {

70 m.isDefined && !m.get.containsField("results")

71 }).map(_.get.toString)

DbObject.scala (http://scaly.googlecode.com/svn/trunk/) Scala · 158 lines

27 package scaly.parabond.db

28 import com.mongodb.casbah.MongoConnection

29 import com.mongodb.casbah.commons.{ MongoDBObject, MongoDBList }

30 import scala.io.Source

31 import java.util.Calendar

54 val mongo = mongodb(COLL_BONDS)

55

56 // Creating an empty MongoDBObject List

57 var list = List(MongoDBObject())

68 val id = details(0).trim.toInt

69

70 val entry = MongoDBObject("id" -> id, "coupon" -> details(1).trim.toDouble, "freq" -> details(2).trim.toInt, "tenor" -> details(3).trim.toInt, "maturity" -> details(4).trim.toDouble)

71

72 mongo.insert(entry)

76

77 // Print the current size of Bond Collection in DB

78 println(mongo.find().size + " documents inserted into collection: "+COLL_BONDS)

79 }

80

MongoU2IActions.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 67 lines

27 }

28

29 def getAllByAppid(appid: Int) = new MongoU2IActionIterator(u2iActionColl.find(MongoDBObject("appid" -> appid)))

30

31 def getAllByAppidAndUidAndIids(appid: Int, uid: String, iids: Seq[String]) = new MongoU2IActionIterator(

32 u2iActionColl.find(MongoDBObject("appid" -> appid, "uid" -> idWithAppid(appid, uid), "iid" -> MongoDBObject("$in" -> iids.map(idWithAppid(appid, _)))))

33 )

34

35 def getAllByAppidAndIid(appid: Int, iid: String, sortedByUid: Boolean = true): Iterator[U2IAction] = {

36 if (sortedByUid)

37 new MongoU2IActionIterator(u2iActionColl.find(MongoDBObject("appid" -> appid, "iid" -> idWithAppid(appid, iid))).sort(MongoDBObject("uid" -> 1)))

38 else

39 new MongoU2IActionIterator(u2iActionColl.find(MongoDBObject("appid" -> appid, "iid" -> idWithAppid(appid, iid))))

demoMongoDb.scala (http://findataweb.googlecode.com/svn/trunk/) Scala · 167 lines

8

9 // use casbah

10 :cp Documents/findataweb/scala/demos/lib/mongo-2.5.1.jar

11 :cp Documents/findataweb/scala/demos/lib/casbah-core_2.8.1-2.1.0.jar

12 :cp Documents/findataweb/scala/demos/lib/casbah-commons_2.8.1-2.1.0.jar

13 :cp Documents/findataweb/scala/demos/lib/casbah-query_2.8.1-2.1.0.jar

14

15 :cp Documents/findataweb/scala/demos/lib/joda-time-1.6.jar

16 :cp Documents/findataweb/scala/demos/lib/scalaj-collection_2.8.0-1.0.jar

17 :cp Documents/findataweb/scala/demos/lib/slf4j-api-1.6.1.jar

18 :cp Documents/findataweb/scala/demos/lib/slf4j-jdk14-1.6.1.jar

25 val mongoConn = MongoConnection()

26

27 val newObj = MongoDBObject("foo" -> "bar",

28 "x" -> "y",

29 "pie" -> 3.14,

Start.scala (https://gitlab.com/thugside/sync) Scala · 132 lines

81 logger.info("Total number of jobs processed: " + jobsProcessed)

82 fetcherCollection.insert(

83 MongoDBObject(

84 "job_status" -> "completed",

85 "progress" -> 100,

MongodbWriterIT.scala (https://github.com/Stratio/Spark-MongoDB.git) Scala · 256 lines

17

18 import com.mongodb._

19 import com.mongodb.casbah.commons.MongoDBObject

20 import com.mongodb.util.JSON

21 import com.stratio.datasource.MongodbTestConstants

231 val dbCollection = mongodbClient.getDB(db).getCollection(collection)

232

233 val dbCursor = dbCollection.find(MongoDBObject("att3" -> "holo"))

234

235 import scala.collection.JavaConversions._

241 mongodbBatchWriter.saveWithPk(dbUpdateIterator)

242

243 val dbCursor2 = dbCollection.find(MongoDBObject("att3" -> "holo"))

244

245 dbCursor2.iterator().toList.foreach { case obj: BasicDBObject =>

Token.scala (https://github.com/BeamStream/BeamstreamPlay.git) Scala · 64 lines

33 def findToken(tokenString: String): List[Token] = {

34 TokenDAO.find(MongoDBObject("tokenString" -> tokenString)).toList

35 }

36

37 def findTokenByUserId(userId: String): List[Token] = {

38 TokenDAO.find(MongoDBObject("userId" -> userId)).toList

39 }

40

45 // def findTokenOnBasisOfUserID(userId: String): List[Token] = {

46 // TokenDAO.find(MongoDBObject("userId" -> new ObjectId(userId))).toList

47 // }

48 //

49 // def isUserRegistered(userId: String) = {

50 // TokenDAO.find(MongoDBObject("userId" -> new ObjectId(userId))).toList.head.used

51 // }

52

ConversionsSpec.scala (git://github.com/ymasory/scala-corpus.git) Scala · 180 lines

63 mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

64

65 val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

66 MongoDBObject("date" -> 1))

83 mongo += MongoDBObject("date" -> jodaDate, "type" -> "joda")

84

85 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "joda"),

86 MongoDBObject("date" -> 1))

131 mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

132

133 val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

134 MongoDBObject("date" -> 1))

146 RegisterJodaTimeConversionHelpers()

147

148 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

149 MongoDBObject("date" -> 1))

Domain.scala (git://github.com/olim7t/mongo-scala.git) Scala · 74 lines

28 class EventRepository {

29

30 def findById(id: ObjectId): Option[Event] = mongoDb("events").findOneByID(id).map(dbToEvent)

31

32 def save(event: Event): Event = {

36 }

37

38 def removeById(id: ObjectId) = mongoDb("events").remove(MongoDBObject("_id" -> id))

39

40 def count = mongoDb("events").size

41

42 def countWithName(name: String) = mongoDb("events").count(MongoDBObject("name" -> name))

43

44 def addSessionToEvent(eventId: ObjectId, session: EventSession) {

ServiceSpec.scala (https://github.com/vfarcic/books-service.git) Scala · 184 lines

3 import com.mongodb.casbah.Imports._

4 import com.mongodb.casbah.MongoClient

5 import com.mongodb.casbah.commons.MongoDBObject

6 import com.novus.salat._

7 import com.novus.salat.global._

174

175 def getBook(id: Int): Book = {

176 val dbObject = collection.findOne(MongoDBObject("_id" -> id))

177 grater[Book].asObject(dbObject.get)

178 }

179

180 def getBooks: List[Book] = {

181 collection.find().toList.map(grater[Book].asObject(_))

182 }

183

MycotrackUrlRewriter.scala (git://github.com/JanxSpirit/mycotrack_mongo.git) Scala · 49 lines

20 case RewriteRequest(

21 ParsePath("projects" :: key :: Nil, "", true, false), _, _) => {

22 val project = Project.find(MongoDBObject("key" -> key))

23 SelectedProject(project)

24 RewriteResponse("events" :: Nil)

34 case RewriteRequest(

35 ParsePath("speciesInfo" :: id :: Nil, "", true, false), _, _) => {

36 val species = Species.find(id)

37 theSpecies(species)

38 RewriteResponse(ParsePath("speciesInfo" :: Nil, "", true, false), Map.empty, true)

41 case RewriteRequest(

42 ParsePath("splitProject" :: id :: Nil, "", true, false), _, _) => {

43 val project = Project.find(id)

44 SelectedProject(project)

45 RewriteResponse(ParsePath("splitProject" :: Nil, "", true, false), Map.empty, true)

casbah_dbobject_sample1.scala (https://github.com/bwmcadams/presentations.git) Scala · 60 lines

32

33 // "Factory" method

34 val constructed: DBObject = MongoDBObject(

35 "foo" -> "bar",

36 "spam" -> "eggs",

46

47 // We showed the builder before

48 val builder = MongoDBObject.newBuilder

49 builder += "foo" -> "bar"

50 builder += "spam" -> "eggs"

57 // Also responds to the 'Map' methods...

58 built += "x" -> "y"

59 built.getOrElse("x", throw new Error("Can't find value for X"))

60 /* res15: AnyRef = y */

61

ManageProject.scala (git://github.com/JanxSpirit/mycotrack_mongo.git) Scala · 62 lines

2

3 import xml.NodeSeq

4 import com.mongodb.casbah.commons.MongoDBObject

5 import _root_.net.liftweb.util.Helpers

6 import com.mycotrack.db.MycoMongoDb

7 import xml.{Group, NodeSeq, Text}

8 import Helpers._

9 import net.liftweb.http.{RequestVar, S, TemplateFinder, SHtml}

10 import com.mycotrack.model.{Species, Project, User}

11 import net.liftweb.common.{Empty, Full}

26 Helpers.bind("project", xhtml,

27 "image" -> {

28 val photo = MycoMongoDb.gridFs.findOne(MongoDBObject("mapped_id" -> project.id))

29 photo match {

30 case None => Text("No QR code found")

Task.scala (git://github.com/Mironor/Play-2.0-Scala-MongoDb-Salat-exemple.git) Scala · 38 lines

22 current.configuration.getString("mongodb.default.db")

23 .getOrElse(throw new PlayException("Configuration error",

24 "Could not find mongodb.default.db in settings"))

25 )("tasks"))

26

27

28 object Task {

29 def all(): List[Task] = TaskDAO.find(MongoDBObject.empty).toList

30

31 def create(label: String): Option[ObjectId] = {

34

35 def delete(id: String) {

36 TaskDAO.remove(MongoDBObject("_id" -> new ObjectId(id)))

37 }

38 }

CasbahDBTestSpecification.scala (git://github.com/mongodb/casbah.git) Scala · 133 lines

93 if (serverIsAtLeastVersion(2, 5)) {

94 mongoClient.getDB("admin").command(

95 MongoDBObject("configureFailPoint" -> "maxTimeAlwaysTimeOut", "mode" -> "alwaysOn"),

96 ReadPreference.Primary

97 )

102 if (serverIsAtLeastVersion(2, 5)) {

103 mongoClient.getDB("admin").command(

104 MongoDBObject("configureFailPoint" -> "maxTimeAlwaysTimeOut", "mode" -> "off"),

105 ReadPreference.Primary

106 )

111 lazy val isReplicaSet = runReplicaSetStatusCommand

112 lazy val isSharded: Boolean = {

113 val isMasterResult = mongoClient.getDB("admin").command(MongoDBObject("ismaster" -> 1))

114 Option(isMasterResult.get("msg")) match {

115 case Some("isdbgrid") => true

MongoSequences.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 21 lines

10 /** Get the next sequence number from the given sequence name. */

11 def genNext(name: String): Int = {

12 val qFind = MongoDBObject("_id" -> name)

13 val qField = MongoDBObject("next" -> 1)

14 val qSort = MongoDBObject()

15 val qRemove = false

16 val qModify = $inc("next" -> 1)

17 val qReturnNew = true

18 val qUpsert = true

19 seqColl.findAndModify(qFind, qField, qSort, qRemove, qModify, qReturnNew, qUpsert).get.getAsOrElse[Number]("next", 0).intValue

20 }

21 }

g8.scala (git://github.com/softprops/ls-server.git) Scala · 143 lines

3 object G8Conversions extends Logged {

4 import com.mongodb.casbah.commons.Imports.ObjectId

5 import com.mongodb.casbah.commons.{MongoDBObject => Obj, MongoDBList => ObjList}

6 import com.mongodb.casbah.{MongoCollection, MongoCursor}

7 import com.mongodb.{BasicDBList, DBObject}

27 import Mongo._

28 import com.mongodb.casbah.commons.Imports.ObjectId

29 import com.mongodb.casbah.commons.{ MongoDBObject => Obj, MongoDBList => ObjList }

30 import com.mongodb.casbah.{ MongoCollection }

31 import com.mongodb.{ BasicDBList, DBObject }

51 templates { c =>

52 log.info("getting templates (page: %s, limit: %s)" format(page, limit))

53 f(cct(paginate(c.find(), page, limit).sort(

54 Obj("username" -> 1, "name"-> 1))))

55 }

732d903592120b02a263c613d17556036f0f2af3UserManager.scala (https://github.com/aliostad/deep-learning-lang-detection.git) Scala · 94 lines

19 def edit_user_act(user_id: String) = Action { request =>

20 val post_map = request.body.asFormUrlEncoded.get // Map[String, List]

21 val query = MongoDBObject("_id" -> user_id)

22

23 var update = MongoDBObject("is_super"->"false")

37

38 def edit_user(user_id: String) = Action {request=>

39 val query = MongoDBObject("_id" -> user_id)

40 val user = DB.colls("User").findOne(query).get

43

44 def del_user_act(user_id: String) = Action{ implicit request =>

45 val query = MongoDBObject("_id" -> user_id)

46 val result = DB.colls("User").remove(query)

47

75

76 val user_id = request.session.get("user_id").get

77 val query_user = MongoDBObject("_id" -> user_id)

78 val user = DB.colls("User").findOne(query_user).get

PlainCasbah.scala (git://github.com/havocp/beaucatcher.git) Scala · 96 lines

39 }

40

41 private def convertObject(obj : Map[String, Any]) : MongoDBObject = {

42 val builder = MongoDBObject.newBuilder

61 }

62

63 override def findOne(collection : MongoCollection) = {

64 val maybeOne = collection.findOne()

67 }

68

69 override def findAll(collection : MongoCollection, numberExpected : Int) = {

70 val all = collection.find()

79 }

80

81 override def findAllAsync(collection : MongoCollection, numberExpected : Int) : BenchmarkFuture = {

82 BenchmarkFuture(threads.submit(new Runnable() {

83 override def run() = {

DataSets.scala (https://github.com/delving/culture-hub.git) Scala · 80 lines

27 case Accepts.Html() => Ok(Template('title -> listPageTitle("dataset"), 'canAdministrate -> DataSet.dao.canAdministrate(connectedUser)))

28 case Accepts.Json() =>

29 val sets = DataSet.dao.findAll()

30 val smallSets = sets.map { set =>

31 Map("key" -> set.spec, "name" -> set.details.name)

40 MultitenantAction {

41 implicit request =>

42 val maybeDataSet = DataSet.dao.findBySpecAndOrgId(spec, configuration.orgId)

43 if (maybeDataSet.isEmpty) {

44 NotFound(Messages("dataset.DatasetWasNotFound", spec))

68 implicit request =>

69 val formats = maybeFormats.map(_.split(",").toSeq.map(_.trim).filterNot(_.isEmpty)).getOrElse(Seq.empty)

70 val query = MongoDBObject("spec" -> Pattern.compile(q, Pattern.CASE_INSENSITIVE))

71 val sets = DataSet.dao.find(query).filter { set =>

NameIndexer.scala (https://gitlab.com/18runt88/twofishes) Scala · 76 lines

28 var nameCount = 0

29 val nameSize = NameIndexDAO.collection.count()

30 val nameCursor = NameIndexDAO.find(MongoDBObject())

31 .sort(orderBy = MongoDBObject("name" -> 1)) // sort by nameBytes asc

Specs2Helpers.scala (git://github.com/mongodb/casbah.git) Scala · 169 lines

34

35 implicit val sizedOptDBObj = new Sized[Option[DBObject]] {

36 def size(t: Option[DBObject]) = t.getOrElse(MongoDBObject.empty).size

37 }

38

58

59 protected def someField(map: Expectable[Option[DBObject]], k: String) = if (k.indexOf('.') < 0) {

60 map.value.getOrElse(MongoDBObject.empty).getAs[AnyRef](k)

61 } else {

62 map.value.getOrElse(MongoDBObject.empty).expand[AnyRef](k)

77 def beDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[DBObject], " is a DBObject", " is not a DBObject")

78

79 def beMongoDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBObject], " is a MongoDBObject", " is not a MongoDBObject")

80

81 def beMongoDBList: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBList], " is a MongoDBList", " is not a MongoDBList")

MongoDBSpecification.scala (git://github.com/mongodb/casbah.git) Scala · 152 lines ✨ Summary

This is a Scala specification class for MongoDB’s Casbah library, providing a set of matcher functions to verify the structure and contents of MongoDB objects, such as documents and lists. These matchers can be used in tests to ensure that MongoDB data conforms to expected formats. They support dot notation and provide various ways to check for specific fields or entries within an object.

24 import org.specs2.matcher.Matchers._

25 import com.mongodb.casbah.util.Logging

26 import com.mongodb.casbah.commons.MongoDBObject

27

28 object `package` {

36 trait CasbahSpecificationBase extends DBObjectMatchers with Logging {

37 implicit val sizedOptDBObj = new Sized[Option[DBObject]] {

38 def size(t: Option[DBObject]) = t.getOrElse(MongoDBObject.empty).size

39 }

40

76 def beDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[DBObject], " is a DBObject", " is not a DBObject")

77

78 def beMongoDBObject: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBObject], " is a MongoDBObject", " is not a MongoDBObject")

79

80 def beMongoDBList: Matcher[AnyRef] = ((_: AnyRef).isInstanceOf[MongoDBList], " is a MongoDBList", " is not a MongoDBList")

ShapefileWriter.scala (https://gitlab.com/18runt88/twofishes) Scala · 107 lines

74 val collection = new ListFeatureCollection(TYPE)

75

76 val total = MongoGeocodeDAO.count(MongoDBObject("hasPoly" -> true))

77

78 val records =

79 MongoGeocodeDAO.find(MongoDBObject("hasPoly" -> true))

80

81 val geomFactory = new GeometryFactory()

UserRepositoryTests.scala (https://github.com/kufi/Filefarmer.git) Scala · 87 lines

1 package ch.filefarmer.tests.repositories

2 import ch.filefarmer.repositories.UserRepository

3 import com.mongodb.casbah.commons.MongoDBObject

4 import ch.filefarmer.poso.User

5 import org.junit.runner.RunWith

20 rep.addUser(user)

21

22 val q = MongoDBObject("_id" -> user.id)

23

24 mongoDB("users").findOne(q) should be('defined)

DataObjectConverter.scala (https://code.google.com/p/sgine/) Scala · 108 lines

5 import com.mongodb.{BasicDBList, DBObject}

6 import annotation.tailrec

7 import com.mongodb.casbah.commons.{MongoDBList, MongoDBListBuilder, MongoDBObject}

8 import collection.mutable.ListBuffer

9

15 */

16 trait DataObjectConverter {

17 def fromDBObject(db: MongoDBObject): AnyRef

18

19 def toDBObject(obj: AnyRef): DBObject

23 private var map = Map.empty[Class[_], DataObjectConverter]

24

25 def fromDBObject[T](db: MongoDBObject) = {

26 val clazz = Class.forName(db.as[String]("class"))

27 val converter = findConverter(clazz)

ConversionsSpec.scala (https://github.com/etorreborre/casbah.git) Scala · 192 lines

97 mongo += MongoDBObject("date" -> jodaDate, "type" -> "joda")

98

99 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "joda"),

100 MongoDBObject("date" -> 1))

125 mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

126

127 val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

128 MongoDBObject("date" -> 1))

145 mongo += MongoDBObject("date" -> jdkDate, "type" -> "jdk")

146

147 val jdkEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

148 MongoDBObject("date" -> 1))

159 RegisterJodaTimeConversionHelpers()

160

161 val jodaEntry = mongo.findOne(MongoDBObject("type" -> "jdk"),

162 MongoDBObject("date" -> 1))

Logs.scala (https://github.com/delving/culture-hub.git) Scala · 44 lines

17 def list(taskId: ObjectId, lastCount: Option[Int]) = MultitenantAction {

18 implicit request =>

19 val cursor: SalatMongoCursor[Log] = Log.dao.find(MongoDBObject("task_id" -> taskId)).limit(500).sort(MongoDBObject("date" -> 1))

20 val (logs, skipped) = if (lastCount != None && lastCount.get > 0) {

21 if (cursor.count - lastCount.get > 100) {

37 implicit request =>

38 {

39 val cursor: SalatMongoCursor[Log] = Log.dao.find(MongoDBObject("task_id" -> taskId)).sort(MongoDBObject("date" -> 1))

40 Ok(cursor.map(log => log.date + "\t" + s"[${log.orgId}] " + log.level.name.toUpperCase + "\t" + log.node + "\t" + log.message).mkString("\n"))

41 }

ProjectDao.scala (https://github.com/JanxSpirit/mycotrack-api.git) Scala · 108 lines

5 import com.novus.salat._

6 import com.novus.salat.global._

7 import com.mongodb.casbah.commons.MongoDBObject

8 import com.mycotrack.api._

9 import model._

18 def getProject(key: ObjectId) = {

19 Future {

20 val q = MongoDBObject("_id" -> key)

21 val dbo = mongoCollection.findOne(q)

34 def updateProject(key: ObjectId, model: Project) = {

35 Future {

36 val query = MongoDBObject("_id" -> key)

37 val update = $addToSet("content" -> model)

38

39 mongoCollection.update(query, update, false, false, WriteConcern.Safe)

40

41 val dbo = mongoCollection.findOne(query)

42 dbo.map(f => grater[ProjectWrapper].asObject(f))

43 }

MongoApps.scala (https://github.com/activetrader/PredictionIO.git) Scala · 85 lines

50 def getAll() = new MongoAppIterator(appColl.find())

51

52 def getByUserid(userid: Int) = new MongoAppIterator(appColl.find(MongoDBObject("userid" -> userid), getFields))

53

54 def getByAppkey(appkey: String) = appColl.findOne(MongoDBObject("appkey" -> appkey), getFields) map { dbObjToApp(_) }

73

74 def updateAppkeyByAppkeyAndUserid(appkey: String, userid: Int, newAppkey: String) = {

75 appColl.findAndModify(MongoDBObject("appkey" -> appkey, "userid" -> userid), MongoDBObject("$set" -> MongoDBObject("appkey" -> newAppkey))) map { dbObjToApp(_) }

76 }

77

78 def updateTimezoneByAppkeyAndUserid(appkey: String, userid: Int, timezone: String) = {

79 appColl.findAndModify(MongoDBObject("appkey" -> appkey, "userid" -> userid), MongoDBObject("$set" -> MongoDBObject("timezone" -> timezone))) map { dbObjToApp(_) }

80 }

81

MongodbReader.scala (https://github.com/Stratio/Spark-MongoDB.git) Scala · 139 lines

92 mongoClientKey = Option(mongoClientResponse.key)

93

94 val emptyFilter = MongoDBObject(List())

95 val filter = Try(queryPartition(filters)).getOrElse(emptyFilter)

96

98 client <- mongoClient

99 collection <- Option(client(config(MongodbConfig.Database))(config(MongodbConfig.Collection)))

100 dbCursor <- Option(collection.find(filter, selectFields(requiredColumns)))

101 } yield {

102 mongoPartition.partitionRange.minKey.foreach(min => dbCursor.addSpecial("$min", min))

123 /**

124 *

125 * Prepared DBObject used to specify required fields in mongodb 'find'

126 * @param fields Required fields

127 * @return A mongodb object that represents required fields.

MongoRepository.scala (http://tratata.googlecode.com/svn/trunk/) Scala · 42 lines

9 import org.scala_tools.time.Imports._

10 import com.mongodb.DBObject

11 import com.mongodb.casbah.commons.MongoDBObject; import com.mongodb.casbah.Imports._; object MongoDataSource {

12 //val mongodbConfigPrefix = "akka.remote.server.server.client.storage.mongodb"

13 val hostName="127.0.0.1" //config.getString(mongodbConfigPrefix+".hostname", "127.0.0.1")

21 class MongoRepository() extends Repository{

22

23 def findOne[T](qr:Query[T]):Option[BasicData]={

24 collection(qr.collectionName).findOne(qr.queryObject).map(create(_,qr.clazz))

25 };

26 def find[T](qr:Query[T]):List[BasicData]={

27 collection(qr.collectionName).find(qr.queryObject).map(create(_,qr.clazz)).toList

SprayMongoAuthenticator.scala (https://github.com/JanxSpirit/mycotrack-api.git) Scala · 57 lines

6 import com.mongodb.casbah.MongoConnection._

7 import com.mongodb.casbah.MongoConnection

8 import com.mongodb.casbah.commons.MongoDBObject

9 import com.mongodb.casbah.commons.Imports._

10 import com.novus.salat._

20

21 def apply(ctx: RequestContext) = {

22 val authHeader = ctx.request.headers.findByType[`Authorization`]

23 val credentials = authHeader.map { case Authorization(credentials) => credentials }

24 authenticate(credentials, ctx) match {

46 case (user, pass) => {

47 val db = MongoConnection()("mycotrack")("users")

48 val userResult = db.findOne(MongoDBObject("username" -> user) ++ ("password" -> pass))

49 userResult.map(grater[BasicUserContext].asObject(_))

50 }

Mongo.scala (https://github.com/mostlygeek/PlayByExample.git) Scala · 50 lines

27

28 /**

29 * looks for a document within mongo, if it can't find it

30 * it will create it and tell the user to reload the page.

31 */

32 def create(id: String) = Action {

33 col.findOneByID(id) match {

34 case None => {

35 // the += operator allows Docs to be added to mongo easily

36 col += MongoDBObject("_id" -> id, "created" -> true)

37 Ok("created: " + id + ", refresh to load record")

38 }

MediaSpec.scala (git://github.com/leodagdag/persistance.git) Scala · 135 lines

45 "find by criteria" in {

46 running(FakeApplication()) {

47 val newPost = Media.findOne(MongoDBObject("title" -> "titre"))

48 newPost mustNotEqual None

49 }

71 "find all" in {

72 running(FakeApplication()) {

73 val all = Media.find(MongoDBObject()).toList

74 all.size mustEqual 13

75 }

82 }

83

84 "find by page" in {

85 running(FakeApplication()) {

86 implicit val dao = Media

CoreWrappersSpec.scala (git://github.com/ymasory/scala-corpus.git) Scala · 178 lines

131 val coll = db("collectoin")

132 coll.drop()

133 coll.insert(MongoDBObject("foo" -> "bar"))

134 coll must notBeNull

135 coll must haveSuperClass[com.mongodb.casbah.MongoCollection]

158 coll.insert(MongoDBObject("foo" -> "bar"))

159 val basicFind = coll.find(MongoDBObject("foo" -> "bar"))

160

161 basicFind must notBeNull

162 basicFind must haveSize(1)

163

164 val findOne = coll.findOne()

165

166 findOne must beSomething

167

168 val findOneMatch = coll.findOne(MongoDBObject("foo" -> "bar"))

169

170 findOneMatch must beSomething

GridFS.scala (git://github.com/mongodb/casbah.git) Scala · 247 lines ✨ Summary

This Scala code defines a set of classes and traits for interacting with MongoDB GridFS, a system for storing large files in a database. It provides methods for creating, reading, and updating files, as well as converting between different date formats. The classes are designed to be used with the MongoDB driver, allowing developers to easily store and retrieve files from a MongoDB database.

211 }

212

213 def findOne[A <% DBObject](query: A): Option[GridFSDBFile] = {

214 filesCollection.findOne(query) match {

222 }

223

224 def findOne(id: ObjectId): Option[GridFSDBFile] = findOne(MongoDBObject("_id" -> id))

225

226 def findOne(filename: String): Option[GridFSDBFile] = findOne(MongoDBObject("filename" -> filename))

MongoDataGetter.scala (git://github.com/btarbox/Log4ScalaFugue.git) Scala · 44 lines

33 override def run() {

34 try {

35 for { x <- conn.find().sort(MongoDBObject("timeColumn" -> "1")); thisTime = x.get(timeColumn); if(thisTime != null)} {

36 val line = x.get(timeColumn).toString

37 messageProcessor ! x.get(msgColumn)

user.scala (git://github.com/whiter4bbit/oauth.git) Scala · 51 lines

21 def create(login: String, password: String): Validation[String, User] = {

22 val user = User(login, password, generateKey, generateKey)

23 if (self.users.find(MongoDBObject("login" -> login)).size == 0) {

24 self.users.insert(MongoDBObject("login" -> login,

36 def find(consumerKey: String): Validation[String, User] = {

37 (for {

38 found <- self.users.findOne(MongoDBObject("consumerKey" -> consumerKey));

39 login <- found.getAs[String]("login");

40 password <- found.getAs[String]("password");

BeerDemo.scala (git://github.com/bfritz/mongodb-from-scala.git) Scala · 57 lines

9 val fridge = conn("indyscala")("beer")

10

11 // we need some beer; let's start with Casbah's MongoDBObject...

12 val guinness: DBObject = MongoDBObject(

17

18 // ...more beer via Scala 2.8 builder

19 val builder =MongoDBObject.newBuilder

20 builder += "name" -> "Bully Porter"

21 builder += "variety" -> "porter"

31

32 // let's add a beer to pick on...

33 val keystoneLight: DBObject = MongoDBObject(

34 "name" -> "Keystone Light",

35 "variety" -> "lager",

43

44 // now where did I put that beer!?

45 fridge.find().foreach { b =>

46 println("Let's drink a %s!".format(b("name")))

47 }

MongoPersister.scala (git://github.com/etaoins/choonweb.git) Scala · 109 lines

11

12 // Create our indexes

13 trackColl.ensureIndex(MongoDBObject("path" -> 1), null, true)

14 trackColl.ensureIndex(MongoDBObject("tag.artist" -> 1))

15 trackColl.ensureIndex(MongoDBObject("tag.album" -> 1))

16 trackColl.ensureIndex(MongoDBObject("tag.title" -> 1))

17 trackColl.ensureIndex(MongoDBObject("keywords" -> 1))

18

19 scanColl.ensureIndex(MongoDBObject("finished" -> -1))

26 react {

27 case AudioFileScanned(relativePath, audioFile) =>

28 def tagInformation(tag : org.jaudiotagger.tag.Tag) : MongoDBObject = {

29 val tagBuilder = MongoDBObject.newBuilder

CasbahQuerying.scala (git://github.com/bwmcadams/mongoScalaWebinar.git) Scala · 54 lines

15 // What about querying? Lets find all the non-US events

16

17 for (x <- mongo.find(MongoDBObject("location.country" ->

18 MongoDBObject("$ne" -> "USA")))) println(x)

23 println("\n\nTesting for existence of Location.Country:")

24

25 for (x <- mongo.find(MongoDBObject("location.country" -> MongoDBObject(

26 "$ne" -> "USA",

27 "$exists" -> true

35 println("\n Querying using DSL Object...")

36

37 for (x <- mongo.find(q)) println(x)

38

39 // It's possible to construct more complex queries too.

48 println("\n Date Query: %s".format(dateQ))

49

50 for (x <- mongo.find(dateQ, MongoDBObject("name" -> true, "date" -> true))) println(x)

51

52 }

DataSetStatistics.scala (https://github.com/delving/culture-hub.git) Scala · 113 lines

22

23 def getStatisticsFile = {

24 hubFileStores.getResource(OrganizationConfigurationHandler.getByOrgId(context.orgId)).findOne(MongoDBObject("orgId" -> context.orgId, "spec" -> context.spec, "uploadDate" -> context.uploadDate))

25 }

26

27 def getHistogram(path: String)(implicit configuration: OrganizationConfiguration): Option[Histogram] = DataSetStatistics.dao.frequencies.

28 findByParentId(_id, MongoDBObject("context.orgId" -> context.orgId, "context.spec" -> context.spec, "context.uploadDate" -> context.uploadDate, "path" -> path)).toList.headOption.

29 map(_.histogram)

30

109 val values = new ChildCollection[FieldValues, ObjectId](collection = fieldValues, parentIdField = "parentId") {}

110

111 def getMostRecent(orgId: String, spec: String, schema: String) = find(MongoDBObject("context.orgId" -> orgId, "context.spec" -> spec, "context.schema" -> schema)).$orderby(MongoDBObject("_id" -> -1)).limit(1).toList.headOption

112

113 }

SprayMongoAuthenticator.scala (https://github.com/ctcarrier/ouchload.git) Scala · 35 lines

6 import com.mongodb.casbah.MongoConnection._

7 import com.mongodb.casbah.MongoConnection

8 import com.mongodb.casbah.commons.MongoDBObject

9 import com.mongodb.casbah.commons.Imports._

10 import com.novus.salat._

24 case (user, pass) => {

25 val db = MongoConnection()("mycotrack")("users")

26 val userResult = db.findOne(MongoDBObject("username" -> user) ++ ("password" -> pass))

27 userResult.map(grater[BasicUserContext].asObject(_))

28 }

User.scala (git://github.com/leodagdag/persistance.git) Scala · 35 lines

26

27 def authenticate(username: String, password: String): Option[User] = {

28 this.findOne(MongoDBObject("username" -> username, "password" -> password))

29 }

30

31 def byUsername(username: String): Option[User] = {

32 this.findOne(MongoDBObject("username" -> username))

33 }

34

MainTest.scala (https://github.com/scorelab/senz.git) Scala · 67 lines

36 // "count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))

37 // collection.insertOne(doc)

38 // collection.find.first().printResults()

39

40 // val collection: MongoCollection[Document] = database.getCollection("movie");

58 // case class Stock (symbol: String, price: Double)

59 //

60 // def buildMongoDbObject(stock: Stock): MongoDBObject = {

61 // val builder = MongoDBObject.newBuilder

PolygonIndexer.scala (https://gitlab.com/18runt88/twofishes) Scala · 59 lines

22 def writeIndexImpl() {

23 val polygonSize = PolygonIndexDAO.collection.count()

24 val usedPolygonSize = MongoGeocodeDAO.count(MongoDBObject("hasPoly" -> true))

25

26 val hasPolyCursor =

27 MongoGeocodeDAO.find(MongoDBObject("hasPoly" -> true))

28 .sort(orderBy = MongoDBObject("_id" -> 1)) // sort by _id asc

41 toFindPolys: Map[Long, ObjectId] = group.filter(f => f.hasPoly).map(r => (r._id, r.polyId)).toMap

42 polyMap: Map[ObjectId, PolygonIndex] = PolygonIndexDAO.find(MongoDBObject("_id" -> MongoDBObject("$in" -> toFindPolys.values.toList)))

43 .toList

44 .groupBy(_._id).map({case (k, v) => (k, v(0))})

User.scala (https://gitlab.com/Memoria/Memoria) Scala · 66 lines

15 val coll = User.db("users")

16

17 def findAll () : mutable.Set[UserModel] = {

18 val result : mutable.Set[UserModel] = mutable.Set[UserModel]()

19 val users = User.coll.find()

31 }

32

33 def findUser (login : String, password : String) : Option[UserModel] = {

34 var result : Option[UserModel] = None

35 val q = MongoDBObject("login" -> login, "password" -> password )

36 val cursor = User.coll.findOne(q)

37 if (cursor.nonEmpty) {

38 result = Some(UserModel(

50 def createUser (userModel : UserModel) : Boolean = {

51 val coll = User.db("users")

52 val builder = MongoDBObject.newBuilder

53 builder += "login" -> userModel.login

54 builder += "password" -> userModel.password

MongoRepository.scala (https://github.com/alphagov/scala-router.git) Scala · 91 lines

8 import uk.gov.gds.router.model._

9 import uk.gov.gds.router.util.Logging

10 import com.mongodb.casbah.commons.MongoDBObjectBuilder

11

12 abstract class MongoRepository[A <: CaseClass with HasIdentity](collectionName: String, idProperty: String)(implicit m: Manifest[A])

24

25 protected def addIndex(index: DBObject, unique: Boolean, sparse: Boolean) =

26 collection.underlying.ensureIndex(index, MongoDBObject(

27 "unique" -> unique,

28 "background" -> true,

45

46 def load(id: String) = {

47 collection.findOne(MongoDBObject(idProperty -> id))

48 }

49

MongoEngineInfos.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 59 lines

22 def insert(engineInfo: EngineInfo) = {

23 // required fields

24 val obj = MongoDBObject(

25 "_id" -> engineInfo.id,

26 "name" -> engineInfo.name,

32

33 // optional fields

34 val optObj = engineInfo.description.map { d => MongoDBObject("description" -> d) } getOrElse MongoUtils.emptyObj

35

36 coll.insert(obj ++ optObj)

37 }

38

39 def get(id: String) = coll.findOne(MongoDBObject("_id" -> id)) map { dbObjToEngineInfo(_) }

40

41 def getAll() = coll.find().toSeq map { dbObjToEngineInfo(_) }

event.scala (git://github.com/whiter4bbit/oauth.git) Scala · 64 lines

16 val logger = LoggerFactory.getLogger(getClass)

17 def add(event: Event, consumerKey: String): Validation[String, Event] = {

18 if (self.events.find(MongoDBObject("name" -> event.name)).size == 0) {

19 self.events.insert(MongoDBObject("name" -> event.name,

31

32 def mine(consumerKey: String): Validation[String, List[Event]] = {

33 self.events.find(MongoDBObject("consumerKey" -> consumerKey)).map((event) => {

34 for {

35 id <- event.getAs[ObjectId]("_id");

55 (for {

56 id <- objectId(eventId);

57 modified <- self.events.findAndModify(MongoDBObject("_id" -> id),

58 MongoDBObject("$addToSet" -> MongoDBObject("attendees" -> consumerKey)))

TransactionBehavior.scala (https://github.com/dong77/MatchEngine.git) Scala · 59 lines

26

27 def getItems(q: QueryTransaction): Seq[Transaction] = {

28 coll.find(mkQuery(q)).sort(DBObject(TID -> -1)).skip(q.cursor.skip).limit(q.cursor.limit).map(toClass(_)).toSeq

29 }

30

32 val market = Market(t.side._1, t.side._2)

33 val side = t.side.ordered

34 MongoDBObject(

35 TID -> t.id, TAKER_ID -> t.takerUpdate.current.userId, TAKER_ORDER_ID -> t.takerUpdate.current.id,

36 MAKER_ID -> t.makerUpdate.current.userId, MAKER_ORDER_ID -> t.makerUpdate.current.id,

39 }

40

41 private def toClass(obj: MongoDBObject) =

42 converter.fromBinary(obj.getAs[Array[Byte]](TRANSACTION).get, Some(classOf[Transaction.Immutable])).asInstanceOf[Transaction]

43

ChildCollectionSpec.scala (https://github.com/ornicar/salat.git) Scala · 155 lines

45 "support finding children by parent id with key includes" in new parentChildContext {

46 ParentDAO.children.findByParentId(parentId = parent1.id, query = MongoDBObject(), keys = MongoDBObject("parentId" -> 1, "y" -> 1)).toList must contain(

47 child1Parent1.copy(x = "", childInfo = ChildInfo()),

48 child2Parent1.copy(x = "", childInfo = ChildInfo()),

49 child3Parent1.copy(x = "", childInfo = ChildInfo())).only

50 ParentDAO.children.findByParentId(parentId = parent2.id, query = MongoDBObject(), keys = MongoDBObject("parentId" -> 1, "y" -> 1)).toList must contain(

51 child1Parent2.copy(x = "", childInfo = ChildInfo()),

52 child2Parent2.copy(x = "", childInfo = ChildInfo())).only

53 ParentDAO.children.findByParentId(parent3.id).toList must beEmpty

54 }

55

62 "support updating children by typed parent id" in new parentChildContext {

63 val newLastUpdated = new DateMidnight(1812, FEBRUARY, 7).toDateTime

64 val updateQuery = MongoDBObject("$set" -> MongoDBObject("childInfo.lastUpdated" -> newLastUpdated))

65 val cr = ParentDAO.children.updateByParentId(parent1.id, updateQuery, false, true)

66

52b2755b63e71e96da1a8aa671a25f1cebba917cLog.scala (https://github.com/aliostad/deep-learning-lang-detection.git) Scala · 94 lines

9

10 import customContext._

11 import com.mongodb.casbah.commons.MongoDBObject

12

13 abstract class Log(

24 def findLatestLog(): List[Log] =

25 Log.find(MongoDBObject()).sort(orderBy = MongoDBObject("_id" -> -1)).toList

26

27 }

50 def findLatestErrorLog(): List[Log] =

51 Log.find(MongoDBObject()).sort(orderBy = MongoDBObject("_id" -> -1)).filter {

52 case _: ErrorLog => true

53 case _ => false

71 def findLatestEventLog(): List[Log] =

72 Log.find(MongoDBObject()).sort(orderBy = MongoDBObject("_id" -> -1)).filter {

73 case _: EventLog => true

74 case _ => false

Database.scala (https://gitlab.com/williamhogman/checklist.git) Scala · 64 lines

18 def ObjectId() = id

19 def deref() = {

20 val findable = implicitly[IdFindable[T]]

21 findable.byId(id)

26 protected def mdbcol : MongoCollection

27

28 protected def find(query: MongoDBObject): Iterator[MongoDBObject] =

29 mdbcol.find(query) map(wrapDBObj)

30

31 protected def findOne(query: MongoDBObject) : Option[MongoDBObject] =

32 mdbcol.findOne(query) map(wrapDBObj)

35 mdbcol.findOneByID(id)

36

37 protected def update(query: MongoDBObject, to: MongoDBObject) =

38 mdbcol.update(query, to)

39

PollResponse.scala (https://bitbucket.org/wbillingsley/ibmongo-2012-old-version-duct-tape-not-maintained.git) Scala · 77 lines

60 readerRef.fetch match {

61 case RefItself(r) => {

62 val ccOpt = sdao.findOne(MongoDBObject("poll" -> pollRef.getId, "reader" -> r.id))

63 ccOpt

64 }

65 case _ => {

66 val ccOpt = sdao.findOne(MongoDBObject("poll" -> pollRef.getId, "session" -> sessionOpt))

67 ccOpt

68 }

71

72 def getPollResponses(pollRef:Ref[Poll]) = {

73 val res = sdao.find(MongoDBObject("poll" -> pollRef.getId))

74 res.toSeq

75 }

UserDAO.scala (https://github.com/michel-kraemer/spamihilator-setup-wizard.git) Scala · 70 lines

41 * @param user the user to convert

42 * @return the database object */

43 private implicit def userToDBObject(user: User): DBObject = MongoDBObject(

44 "userName" -> user.userName,

45 "passwordHash" -> user.passwordHash,

49 )

50

51 override def find(): Iterable[User] = coll map toUser

52

53 /** Finds a user with the given name

57 def find(userName: String): Option[User] =

58 coll.findOne(MongoDBObject("userName" -> userName)) map toUser

59

60 def insert(user: User) {

66 * user's ID must refer to an existing database item. */

67 def update(user: User) {

68 coll.update(MongoDBObject("_id" -> user.id), user)

69 }

70 }

MongoDBDatastore.scala (https://code.google.com/p/sgine/) Scala · 86 lines

8 import com.mongodb.casbah.commons.Implicits._

9 import org.sgine.reflect.EnhancedClass

10 import com.mongodb.casbah.commons.{MongoDBObjectBuilder, MongoDBObject}

11 import com.mongodb.DBObject

12 import org.bson.types.ObjectId

25 }

26

27 protected def deleteInternal(id: UUID) = collection.findAndRemove(MongoDBObject("_id" -> id)) != None

28

29 override def clear() = collection.dropCollection()

65 def all = collection.find().map(entry => DataObjectConverter.fromDBValue(entry)).asInstanceOf[Iterator[T]]

66

67 private def toDotNotation(pre: String, values: MongoDBObject, builder: MongoDBObjectBuilder = MongoDBObject.newBuilder): DBObject = {

68 if (values.isEmpty) {

69 builder.result()

OnlineUserCacheTest.scala (https://github.com/BeamStream/BeamstreamPlay.git) Scala · 62 lines

6 import com.sun.org.apache.xalan.internal.xsltc.compiler.ForEach

7 import org.scalatest.BeforeAndAfter

8 import com.mongodb.casbah.commons.MongoDBObject

9 import org.bson.types.ObjectId

10 import java.text.DateFormat

37 OnlineUserCache.setOnline(userId.get.toString(), 10000)

38 OnlineUserCache.setOffline(userId.get.toString())

39 assert(OnlineUserDAO.find(MongoDBObject()).toList(0).onlineUsers.size === 0)

40 OnlineUserCache.setOffline(userId.get.toString())

41 assert(OnlineUserDAO.find(MongoDBObject()).toList(0).onlineUsers.size === 0)

47 val userId = User.createUser(user)

48 OnlineUserCache.setOnline(userId.get.toString(), 10000)

49 assert(OnlineUserDAO.find(MongoDBObject()).toList(0).onlineUsers.size === 1)

50 OnlineUserCache.setOnline(userId.get.toString(), 10000)

51 assert(OnlineUserDAO.find(MongoDBObject()).toList(0).onlineUsers.size === 1)

MongoDAO.scala (https://bitbucket.org/marcromera/dsbw-1213t.git) Scala · 61 lines

7 import com.mongodb.MongoException.DuplicateKey

8 import com.novus.salat.Context

9 import com.mongodb.casbah.commons.MongoDBObject

10 import dsbw.mongo.SalatContext.ctx

11

30 }

31

32 def findOne[T<: AnyRef](query:Map[String,T]): Option[ObjectType] = salatDao.findOne(query)

33

34 def findOneByID(id:ObjectId): Option[ObjectType] = salatDao.findOneByID(id)

36 def findByIds(ids:Set[ObjectId]) = salatDao.find("_id" $in ids).toSet

37

38 def findAll = salatDao.find((MongoDBObject.empty))

39

40 def update[T<: AnyRef](query:Map[String,T],update:MongoDBObject,multi:Boolean=true) {

Post.scala (git://github.com/leodagdag/persistance.git) Scala · 76 lines

41

42 def addComment(id: ObjectId, comment: Comment) {

43 val post = this.findOneByID(id)

44 post match {

45 case Some(post) =>

54 }

55

56 def featured: Option[Post] = Post.findOne(MongoDBObject("featured" -> true))

57

58 override def update[A <: DBObject](q: A, post: Post)(implicit dao: SalatDAO[Post, ObjectId]) {

72

73 def updateFeatured() {

74 collection.updateMulti(MongoDBObject("featured" -> true), $set("featured" -> false))

75 }

76 }

EntityMentionAlignmentService.scala (https://github.com/riedelcastro/cmon-noun.git) Scala · 102 lines

21

22 def entityIdsFor(mentionId: Any): TraversableOnce[Any] = {

23 for (dbo <- coll.find(MongoDBObject("mention" -> mentionId))) yield {

24 dbo.as[String]("entity")

25 }

34

35 def mentionIdsFor(entityId: Any): TraversableOnce[Any] = {

36 for (dbo <- coll.find(MongoDBObject("entity" -> entityId))) yield {

37 dbo.as[Any]("mention")

38 }

40

41 def mentionsIdsFor(entityIds: Stream[Any]): TraversableOnce[Alignment] = {

42 for (dbo <- coll.find(MongoDBObject("entity" -> MongoDBObject("$in" -> entityIds)))) yield {

43 val m = dbo.as[Any]("mention")

44 val e = dbo.as[Any]("entity")

Settings04.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 243 lines

49 case "YES" => {

50 engines map { engine =>

51 engineColl.update(MongoDBObject("_id" -> engine.as[Int]("_id")), MongoDBObject("$set" -> MongoDBObject("infoid" -> engine.as[String]("enginetype")), "$unset" -> MongoDBObject("enginetype" -> 1)))

52 }

53 println("Done")

113 val evalid = eval.as[Int]("_id")

114 println(s"Remove obsolete fields for OfflineEval ID = $evalid")

115 offlineEvalColl.update(MongoDBObject("_id" -> evalid), MongoDBObject("$unset" -> MongoDBObject("trainingsize" -> 1, "testsize" -> 1, "timeorder" -> 1)) )

116 }

117 println("Done")

136 val evalid = eval.as[Int]("_id")

137 println(s"Update OfflineEval ID = $evalid with 'iterations'")

138 offlineEvalColl.update(MongoDBObject("_id" -> evalid), MongoDBObject("$set" -> MongoDBObject("iterations" -> 1)) )

139 }

140 println("Done")

MongoOfflineTunes.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 92 lines

9 class MongoOfflineTunes(db: MongoDB) extends OfflineTunes {

10

11 private val emptyObj = MongoDBObject()

12 private val offlineTuneColl = db("offlineTunes")

13 private val seq = new MongoSequences(db)

49

50 // optional fields

51 val createtimeObj = offlineTune.createtime.map(x => MongoDBObject("createtime" -> x)).getOrElse(emptyObj)

52 val starttimeObj = offlineTune.starttime.map(x => MongoDBObject("starttime" -> x)).getOrElse(emptyObj)

61

62 def get(id: Int): Option[OfflineTune] = {

63 offlineTuneColl.findOne(MongoDBObject("_id" -> id), getFields) map { dbObjToOfflineTune(_) }

64 }

65

66 def getAll() = new MongoOfflineTuneIterator(offlineTuneColl.find())

67

68 def getByEngineid(engineid: Int): Iterator[OfflineTune] = new MongoOfflineTuneIterator(offlineTuneColl.find(MongoDBObject("engineid" -> engineid), getFields))

69

70 def update(offlineTune: OfflineTune, upsert: Boolean = false) = {

ServiceRegister.scala (https://gitlab.com/SharkyLV/Mirio.git) Scala · 40 lines

22 override def receive = {

23 case RegisterServiceEvent(service, id) =>

24 serviceCol.insert(MongoDBObject("service"->id,"path"->service.path.toString))

25 println("Registered "+service.toString())

26

27 case ListServicesEvent() =>

28 val toList = serviceCol.find("path" $exists true)

29 val strings: Iterator[String] = for (x <- toList) yield x.getAsOrElse[String]("path", "").toString

30 sender ! ListServicesResponse(strings)

MongoEngines.scala (https://github.com/activetrader/PredictionIO.git) Scala · 76 lines

48 }

49

50 def get(id: Int) = engineColl.findOne(MongoDBObject("_id" -> id), getFields) map { dbObjToEngine(_) }

51

52 def getAll() = new MongoEngineIterator(engineColl.find())

53

54 def getByAppid(appid: Int) = new MongoEngineIterator(engineColl.find(MongoDBObject("appid" -> appid)).sort(MongoDBObject("name" -> 1)))

55

56 def getByAppidAndName(appid: Int, name: String) = engineColl.findOne(MongoDBObject("appid" -> appid, "name" -> name)) map { dbObjToEngine(_) }

73 def deleteByIdAndAppid(id: Int, appid: Int) = engineColl.remove(MongoDBObject("_id" -> id, "appid" -> appid))

74

75 def existsByAppidAndName(appid: Int, name: String) = engineColl.findOne(MongoDBObject("name" -> name, "appid" -> appid)) map { _ => true } getOrElse false

76 }

77

Blog.scala (git://github.com/leodagdag/persistance.git) Scala · 169 lines

9

10 import org.bson.types.ObjectId

11 import com.mongodb.casbah.commons.MongoDBObject

12

13 import models._

83 Action {

84 implicit request =>

85 val post = Post.findOneByID(ObjectId.massageToObjectId(id))

86 post match {

87 case Some(post) => Ok(html.blog.show(post))

94 Action {

95 implicit request =>

96 val post = Post.findOneByID(ObjectId.massageToObjectId(id))

97 post match {

98 case Some(post) => Ok(toJson(Post.writes(post)))

ExampleUtils.scala (https://github.com/Stratio/Spark-MongoDB.git) Scala · 84 lines

18 import com.mongodb.QueryBuilder

19 import com.mongodb.casbah.MongoClient

20 import com.mongodb.casbah.commons.{MongoDBList, MongoDBObject}

21 import com.stratio.datasource.mongodb.examples.DataFrameAPIExample._

22 import org.apache.spark.sql.SQLContext

65 for (a <- 1 to 10) {

66 collection.insert {

67 MongoDBObject("id" -> a.toString,

68 "age" -> (10 + a),

69 "description" -> s"description $a",

76 collection.update(QueryBuilder.start("age").greaterThan(14).get, MongoDBObject(("$set", MongoDBObject(("optionalField", true)))), multi = true)

77 collection.update(QueryBuilder.start("age").is(14).get, MongoDBObject(("$set", MongoDBObject(("fieldWithSubDoc", MongoDBObject(("subDoc", MongoDBList("foo", "bar"))))))))

78 }

79

DeviceController.scala (git://github.com/joakim666/simple-scheduler.git) Scala · 34 lines

3 import scala.collection.mutable.HashMap

4 import org.fusesource.scalate.TemplateEngine

5 import com.mongodb.casbah.commons.MongoDBObject

6 import org.slf4j.LoggerFactory

7 import net.morrdusk.model.{Event, EventDao, DeviceModel}

20 val deviceEvents = new HashMap[Device, List[Event]]

21 devices.foreach(d => {

22 val events = EventDao.find(ref = MongoDBObject("deviceId" -> d.id)).toList

23 deviceEvents += d -> events

24 })

MongoUsers.scala (https://github.com/SNaaS/PredictionIO.git) Scala · 98 lines

58

59 def updateEmail(id: Int, email: String) = {

60 userColl.update(MongoDBObject("_id" -> id), MongoDBObject("$set" -> MongoDBObject("email" -> email)))

61 }

62

66

67 def updatePasswordByEmail(email: String, password: String) = {

68 userColl.update(MongoDBObject("email" -> email), MongoDBObject("$set" -> MongoDBObject("password" -> password)))

69 }

70

71 def confirm(confirm: String) = {

72 userColl.findAndModify(MongoDBObject("confirm" -> confirm), MongoDBObject("$unset" -> MongoDBObject("confirm" -> 1))) map { dbObjToUser(_) }

73 }

74

Registration.scala (https://bitbucket.org/wbillingsley/ibmongo-2012-old-version-duct-tape-not-maintained.git) Scala · 66 lines

55 def findByReader(rid:ObjectId) = {

56 val cursor = sdao.find(MongoDBObject("reader" -> rid))

57 cursor.toSeq

58 }

60 def findByReaderAndBook(r:Ref[Reader], b:Ref[Book]):TraversableOnce[Registration] = {

61 (for (rid <- r.getId; bid <- b.getId) yield {

62 sdao.find(MongoDBObject("reader" -> rid, "book" -> bid))

63 }) getOrElse Seq.empty[Registration]

64 }

Presentation.scala (https://bitbucket.org/wbillingsley/ibmongo-2012-old-version-duct-tape-not-maintained.git) Scala · 71 lines

52 val idOpt = entry.getId

53 val result = idOpt map { oid =>

54 val ccSeq = sdao.find(MongoDBObject("entries" -> oid))

55 ccSeq.toSeq

56 }

MongoUsers.scala (https://github.com/activetrader/PredictionIO.git) Scala · 71 lines

2

3 import io.prediction.commons.MongoUtils.{emptyObj, mongoDbListToListOfString, idWithAppid}

4 import io.prediction.commons.MongoUtils.{attributesToMongoDBObject, getAttributesFromDBObject}

5 import io.prediction.commons.appdata.{User, Users}

6

21 val ct = MongoDBObject("ct" -> user.ct)

22 val lnglat = user.latlng map { l => MongoDBObject("lnglat" -> MongoDBList(l._2, l._1)) } getOrElse emptyObj

23 val inactive = user.inactive map { i => MongoDBObject("inactive" -> i) } getOrElse emptyObj

28 }

29

30 def get(appid: Int, id: String) = userColl.findOne(MongoDBObject("_id" -> idWithAppid(appid, id))) map { dbObjToUser(_) }

31

32 def getByAppid(appid: Int) = new MongoUsersIterator(userColl.find(MongoDBObject("appid" -> appid)))

33

34 def update(user: User) = {

35 val id = MongoDBObject("_id" -> idWithAppid(user.appid, user.id))

36 val appid = MongoDBObject("appid" -> user.appid)

TemplatedDao.scala (https://github.com/nexus49/invsys.git) Scala · 99 lines

13 def fac(dbObject: DBObject, template: Template): Templated

14

15 def findAll(): List[Templated] = {

16 val templates = Template.findAll

21 val collection = CollectionFactory.getCollection(t.collectionName)

22

23 for (result <- collection.find) {

24 val item = fac(result, t)

25 values += (item)

30 }

31

32 def findAll(template: Template): List[Templated] = {

33 val collection = CollectionFactory.getCollection(template.collectionName)

34 val values = new mutable.ListBuffer[Templated]

35 val query = MongoDBObject.apply(CollectionFactory.templateIdColumn -> template.id)

36 val rslt = collection.find(query)

CommonDao.scala (https://github.com/apetheriotis/log-tuc.git) Scala · 100 lines

4 import com.mongodb.DBObject

5 import com.mongodb.casbah.MongoCollection

6 import com.mongodb.casbah.commons.MongoDBObject

7

8 abstract class CommonDao[T](val db: com.mongodb.casbah.MongoDB = MongoFactory.mongoClient) {

33 */

34 protected def getOne: Option[MongoCollection#T] = {

35 db(getCollectionName).findOne()

36 }

37

47 if (orderBy != None) {

48 val order = if (asc.get) 1 else -1

49 val orderQ = MongoDBObject(orderBy.get -> order)

50 db(getCollectionName).find().sort(orderQ).skip(offset).limit(limit)

51 } else {

52 db(getCollectionName).find().skip(offset).limit(limit)

53 }

54 }

CasbahExamples.scala (https://bitbucket.org/Tolsi/scala-school-2018-2.git) Scala · 69 lines

33 }

34

35 val cursor = collectionClient.find(MongoDBObject("params.x" -> 15))

36

37 val ids = cursor.map { o =>

49 rangeCursor.close()

50

51 val writeResult: WriteResult = collectionClient.insert(MongoDBObject("_id" -> "0011", "params" -> MongoDBObject("x" -> 1, "y" -> List(0, 0, 1))))

52 writeResult.getN

53 writeResult.isUpdateOfExisting

54 writeResult.getUpsertedId

55

56 val removedDoc: Option[DBObject] = collectionClient.findAndRemove(MongoDBObject("_id" -> "001"))

57 print(removedDoc)

58

Extractors.scala (https://github.com/ostewart/salat.git) Scala · 124 lines

53 override def after(path: String, t: TypeRefType, pt: TypeRefType, value: Any)(implicit ctx: Context) = value match {

54 case map: scala.collection.Map[String, _] => {

55 val builder = MongoDBObject.newBuilder

56 map.foreach {

57 case (k, el) =>

84 def transform(path: String, t: TypeRefType, value: Any)(implicit ctx: Context) = value match {

85 case cc: CaseClass => ctx.lookup_!(path, cc).asInstanceOf[Grater[CaseClass]].asDBObject(cc)

86 case _ => MongoDBObject("failed-to-convert" -> value.toString)

87 }

88 }

Models.scala (https://github.com/delving/culture-hub.git) Scala · 158 lines

63 val values = List(INFO, ERROR)

64

65 def valueOf(what: String) = values find { _.name == what }

66 }

67

84 def pathExists = new File(path).exists()

85

86 def isCancelled = Task.dao(orgId).findOne(MongoDBObject("_id" -> _id, "state.name" -> TaskState.CANCELLED.name)).isDefined

87

88 override def toString = "Task[%s] type: %s, path: %s, params: %s".format(_id, taskType.name, path, params.toString)

103 def list(taskType: TaskType) = find(MongoDBObject("taskType.name" -> taskType.name)).toList

104

105 def list(state: TaskState) = find(MongoDBObject("state.name" -> state.name, "node" -> getNode)).sort(MongoDBObject("queuedAt" -> 1)).toList

106

107 def listAll() = find(MongoDBObject()).sort(MongoDBObject("queuedAt" -> 1)).toList