Frage

I have 1 problem and 1 question when using BSONDocument getAs.

Whenever I try to access the value l in the format below by calling this:

docFound.getAs[Int]("v.1.0.2013.9.9.l") 

it returns None. However if I do:

docFound.getAs[BSONDocument]("v") 

it returtns a valid BSONDocument for the whole v section. What is wrong in my first call? Does reactivemongo support path traversal?

BSONDocument: {
  v: {
    1.0: {
      2013: {
        9: {
          9: {
            l: BSONInteger(0),
            s: BSONInteger(8)
          }
        }
      }
    }
  }
}

The second question is: I find a document in DB with the following filter:

BSONDocument(
"_id" -> 0,
"v.1.0.2013.9.9.l" -> 1)

But it seems like instead of extracting just these values "_id" & "l" it extracts the whole document. When I do BSONDocument.pretty(foundDoc) I see the whole document, not just "l" value that I have requested. Please clarify if it is even worth specifying fields I am interested in if it always downloads the whole document.

Thanks.

War es hilfreich?

Lösung

It seems like according to the sources it is not supported in reactivemongo. So I have created a quick helper:

def getAsByPath[T](path: String, doc: BSONDocument)
       (implicit reader: BSONReader[_ <: BSONValue, T]): Option[T] = {
  val pathChunks = path.split('.')
  var pathIndex = 0
  var curDoc: Option[BSONDocument] = Some(doc)
  var currentChunk = ""

  while(pathIndex != pathChunks.size) {
    currentChunk += pathChunks(pathIndex)

    // If this is the last chunk it must be a value
    // and if previous Doc is valid let's get it
    if (pathIndex == pathChunks.size - 1 && curDoc != None)
      return curDoc.get.getAs[T](currentChunk)

    val tmpDoc = curDoc.get.getAs[BSONDocument](currentChunk)
    if (tmpDoc != None) {
      currentChunk = ""
      curDoc = tmpDoc
    } else {
      // We need to support this as sometimes doc ID 
      // contain dots, for example "1.0"
      currentChunk += "."
    }

    pathIndex += 1
  }

  None
}

However my second question is still valid. If someone knows please let me know.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top