0

I have a problem using MongoDb through Java I'd like to show my piece program

DBCollection coll = db.getCollection("datatrain");
DBCursor cursor = coll.find();
Iterator<DBObject> dbo = cursor.iterator();
while (dbo.hasNext()) {
  double column1 = (double) dbo.next().get("column1");
  System.out.println(column1); //result show as I expected
}
System.out.println(column1); //only first document printed and local variable error

Is there any method to get data in all document outside while? I know the column1 inside while is a list and I want to use it outside while to become array. I've tried use toArray but it always give me error. Any good manner to use toArray in program?

Community
  • 1
  • 1
newcomers
  • 17
  • 1
  • 10

2 Answers2

0

With mongo-java-driver 3.2+, you can try creating a list of Documents and then iterate through all to print your specific values. A sample here would be -

Your document within datatrain collection could be of type

{
    "column1":123124123
}

Its corresponding model shall be declared as:

public class DataTrain {
    double column1;

    public double getColumn1() {
        return column1;
    }

    public void setColumn1(double column1) {
        this.column1 = column1;
    }
}

Then you can use the following with your MongoClient initialized as:

MongoDatabase database = mongoClient.getDatabase(databaseName); //get Db

MongoCollection<DataTrain> collection = database.getCollection(collectionName, DataTrain.class); // get Collection

List<DataTrain> dataTrainDocuments = Lists.newArrayList(collection.find()); // find and store the documents

//iterate through and access the column1 attribute of all
dataTrainDocuments.forEach(dataTrainObject -> System.out.println(dataTrainObject.getColumn1()));

Edit: You shall implement a code for the object model defined by you:

public class DataTrainCodec implements Codec<DataTrain> {

    private DocumentCodec dataTrainCodec;

    public DataTrainCodec() {
        this.dataTrainCodec = new DocumentCodec();
    }

    @Override
    public void encode(BsonWriter writer, DataTrain dataTrain, EncoderContext encoderContext) {
        org.bson.Document bsonDocument = new org.bson.Document();
        long column1 = dataTrain.getColumn1();
        bsonDocument.put("column1", column1);
        dataTrainCodec.encode(writer, bsonDocument, encoderContext);
    }

    @Override
    public Class<DataTrain> getEncoderClass() {
        return DataTrain.class;
    }

    @Override
    public DataTrain decode(BsonReader reader, DecoderContext decoderContext) {
        org.bson.Document bsonDocument = documentCodec.decode(reader, decoderContext);
        DataTrain dataTrain = new DataTrain();
        dataTrain.setColumn1(bsonDocument.getLong("column1");
        return document;
    }

 }

and register this to your MongoClient as:

MongoClientOptions mco = new MongoClientOptions.Builder()
            .codecRegistry(CodecRegistries.fromCodecs(new DataTrainCodec())).build();
new MongoClient(new ArrayList<ServerAddresses>(), mco);
Naman
  • 27,789
  • 26
  • 218
  • 353
  • I've try on Eclipse but your Lists on Lists.newArrayList cannot be resolved. Should I make initiation to Lists? – newcomers Aug 10 '17 at 06:07
  • this would help you with that https://stackoverflow.com/questions/6416706/easy-way-to-change-iterable-into-collection – Naman Aug 10 '17 at 08:43
  • I add the guava.jar and there's no error anymore but when I run, it get an exception, _org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class mongodbprj01.InsertDrive$DataTrain._ What is that mean? – newcomers Aug 10 '17 at 10:22
  • I already use your suggestion, but it returns an error on documentCodec.decode _(cannot be resolved)_. Do I miss some lib jar? I think you just typo and I change to DocumentCodec.decode but it returns an error too _(Cannot make a static reference to the non-static method decode(BsonReader, DecoderContext) from the type DocumentCodec)_. Also error in my MongoClient register _(The constructor MongoClient(ArrayList, MongoClientOptions) is undefined)_ – newcomers Aug 11 '17 at 07:49
  • @newcomers what version of mongodb-java-driver are you using? – Naman Aug 11 '17 at 09:06
  • I use 3.4.2 version of mongodb-java-driver. why? – newcomers Aug 11 '17 at 10:06
0

Maybe there is efficient way but this solve my problem:

List<Document> matrixes = coll.find().into(new ArrayList<Document>());

        ArrayList<Double> myArray = new ArrayList<Double>();

        for (Document matrix : matrixes) {

            Double column1 = matrix.getDouble("column1");
            myArray.add(column1);
            Double column2 = matrix.getDouble("column2");
            myArray.add(column2);
            Double column3 = matrix.getDouble("column3");
            myArray.add(column3);
            Double column4 = matrix.getDouble("column4");
            myArray.add(column4);
            Double column5 = matrik.getDouble("column5");
            myArray.add(column5);
        }

        myArray.toArray();

I just convert it to ArrayList.

newcomers
  • 17
  • 1
  • 10