Iterate through an array of strings extracted from MongoDB

I am using the MongoKitten library to extract documents from mongoDB.

In my mongoDB there is the following document:

{
    ...
    foo: ["A", "B"]
    ...
}

I can request db, but I cannot go through the array of fooreturned documents. For example, let's say that I save the results of my query to mongoDocs.

for Doc in mongoDocs {
    print(Doc["foo"] as Any) // prints ["A", "B"]
    var tempFoos = [String]()
    for foo in Doc["foo"] { // gives error: Type 'Value' does not conform to protocol "Sequence"
        print("Foo: " + foo)
        tempFoos.append(foo)
     }
}

I understand the error. Basically, my array foodoes not conform to the Sequence protocol, which allows me to iterate over it. But how can I fix this?

Change . This uses the code that I use to get mongoDocs. I printed the results and used other properties. I just can't repeat this array.

mongoDocs = try self.geographiesCollection!.find(matching: q, projecting: projection, limitedTo: 100)

MongoKitten. Cursor<Document>

+4
3

, framework . MongoKitten 27

, .

" MongonKitten BSON () ."

" BSON - 0 x, , . Value , , , t Sequence.

- Value. , Value , , , - . : "

for (key, val) in doc["vals"].document {
   print("Value is \(val)")
}
+2

:

for Doc in mongoDocs {
    guard let arr = Doc["foo"] as? [String] else { continue }
    for foo in arr {
        // do your things
    }
}
+1

I think you are using BSON 3 . Value- this is a listing with several cases, which you can see here here . Here is my hit on him:

for doc in mongoDocs {
    guard case Value.array(let fooArray)? = doc["foo"] {
        fatalError("doc[\"foo\"] is not an array")
    }

    print(fooArray)
}
0
source

Source: https://habr.com/ru/post/1669890/


All Articles