logo
down
shadow

see the content of a .bson file using java


see the content of a .bson file using java

By : user2954478
Date : November 22 2020, 10:31 AM
Hope that helps You can easily read/parse a bson file in Java using a BSONDecoder instance such as BasicBSONDecoder or DefaultBSONDecoder. These classes are included in mongo-java-driver.
Here's a simple example of a Java implementation of bsondump.
code :
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.bson.BSONDecoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;



public class BsonDump {

    public void bsonDump(String filename) throws FileNotFoundException {
        File file = new File(filename);
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        BSONDecoder decoder = new BasicBSONDecoder();
        int count = 0;
        try {
            while (inputStream.available() > 0) {

                BSONObject obj = decoder.readObject(inputStream);
                if(obj == null){
                    break;
                }
                System.out.println(obj);
                count++;

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
        System.err.println(String.format("%s objects read", count));
    }

    public static void main(String args[]) throws Exception {

        if (args.length < 1) {
            //TODO usage
            throw new IllegalArgumentException("Expected <bson filename> argument");
        }
        String filename = args[0];
        BsonDump bsonDump = new BsonDump();
        bsonDump.bsonDump(filename);

    }

}


Share : facebook icon twitter icon
Write some part of a bson file into another bson file in java

Write some part of a bson file into another bson file in java


By : haekal
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have a bson file,(a.bson). I want to read this file and extract some part of it and then save these parts into another BSON file (b.bson). Currently, I can read my source file (a.bson) using org.bson.BSONEncoder and extract my favorite parts of it (e.g., key1 and key2 for each row of source fila). Now I want to save these data in another bson file (b.bson). In fact, I need to save this data in a bson file because this file has structure a I can easily check rows have contains spacial value or not. I write this code and , For example if you want 2% (select randomly) data from source file
code :
File file = new File("a.bson");
        String path = "b.bson";
        BasicBSONEncoder encoder =  new BasicBSONEncoder();
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        BSONDecoder decoder = new BasicBSONDecoder();  
        try {
            while (inputStream.available() > 0) {
                BSONObject bsonSingleRow = decoder.readObject(inputStream);                
                c = bsonSingleRow.get("yourKey").toString();
                    if (Math.random()> .98))
                    Files.write(Paths.get(path), encoder.encode(bsonSingleRow),StandardOpenOption.CREATE, StandardOpenOption.APPEND);                        
                }                                                
            }
        } catch (IOException e) {
            ...
        }
pymongo typeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument

pymongo typeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument


By : Яна Гезь
Date : March 29 2020, 07:55 AM
wish helps you Check out this bulk insert example from MongoDB:s webpage. Skip the json.dumps call (which turns your array of documents into a json formatted string) and insert odbcArray directly:
code :
mongoImp = dbo.insert_many(odbcArray)
Trying to read BSON file, get bson.errors.InvalidBSON: objsize too large

Trying to read BSON file, get bson.errors.InvalidBSON: objsize too large


By : user2119044
Date : March 29 2020, 07:55 AM
I wish this helpful for you I am currently trying to read a bson file to import it into a database. I can already read the file and print it as as bytes, but I end up just getting an bson.errors.InvalidBSON: objsize too large error.
code :
print(content)

b'[{"_id": {"$oid": "5bf3cf511c9d44000088c376"}, "some": "sort of"}, {"_id": {"$oid": "5bf3cf5c1c9d44000088c377"}, "test": "data"}]'
with zip.open(name) as myfile:
    content = myfile.read()
    print(content)
    print(bson.json_util.loads(content))
    #         ^--------------^
    #                | this stuff
Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using


By : Majid Memari
Date : March 29 2020, 07:55 AM
I wish this helpful for you I am getting the below error: , Find in npm module mongodb:
How to write sequence of Bson to file with MongoDB Java Driver

How to write sequence of Bson to file with MongoDB Java Driver


By : nix
Date : March 29 2020, 07:55 AM
Any of those help MongoDB GridFS is a specification for storing and retrieving files.
Use GridFS to store a file « GridFS uses two collections to save a file to a database: fs.files and fs.chunks. Based on the size of the file the data get stored into multiple individual “chunks”. * MongoDB Files using GridFS. Refer to MyPost
code :
public static void main(String[] args) throws IOException {
    mongoDB_GRIDFS("D:\\Yash\\JavaCSV.csv");
}
public static void mongoDB_GRIDFS(String csvlocation) throws IOException{
    Mongo Mongo = new Mongo( "localhost" , 27017 ); // Connect to MongoDB
    DB db = Mongo.getDB( "DBName" ); // Get database
    String bucketName = "BucketName";
    GridFS gridFs = new GridFS(db,bucketName); //Create instance of GridFS implementation  
    String imageName = "image1";
    upload(gridFs, csvlocation, imageName);
    download(gridFs, imageName);     
    Mongo.close();
}
public static void upload(GridFS gridFs, String csvlocation, String imageName) throws IOException{
    GridFSInputFile gridFsInputFile = gridFs.createFile(new File(csvlocation));
    gridFsInputFile.setId("777");
    gridFsInputFile.setFilename(imageName); //Set a name on GridFS entry
    gridFsInputFile.save(); //Save the file to MongoDB
}
public static void download(GridFS gridFs, String imageName) throws IOException{
    GridFSDBFile outputImageFile = gridFs.findOne(imageName);
    String outcsvLocation = "D:\\Yash\\mongoCSV.csv";//Location of the file read from MongoDB to be written
    outputImageFile.writeTo(new File(outcsvLocation));
}
DBObject dbObj = new Document("myKey", "myValue");
String db_json = com.mongodb.util.JSON.serialize( dbObj );

DBObject bson = ( DBObject ) com.mongodb.util.JSON.parse( jsonData );
System.out.println("BSON Object : "+ bson);
BSON Object : [ { "Key2" : "21" , "Key1" : "11" } , { "Key2" : "22" , "Key1" : "12"}]
Json : {"K1":"V1","K2":"V2"}
Map : {K1=V1, K2=V2}
Related Posts Related Posts :
  • Forcefully terminating a thread I didn't write in Java
  • Issue with ojdbc jar in Maven
  • String array length java
  • Java basic compilation error
  • Inquiry about writing a Char via ByteBuffer
  • Getting unexpected results when type casting between long and double
  • Variable throws variable might not have been initialized error
  • Start/stop java application from an external script
  • Confusion in declaring String Objects
  • What are some ways to do multi-core programming on Android, not just multi-thread?
  • hibernate - process scoped identity
  • Null Pointer Exception on getGraphics()
  • Can we print a java message on console without using main method, static variable and static method?
  • sending text from editText to ListView (2 activities)
  • Transfer value from JList to another class in Java
  • Creating 2 streams with one socket
  • How measure time stolen from virtual machine, in Scala/Java?
  • How can I programmatically generate keypress events?
  • org.apache.commons.net.ssh documentation
  • Implementation of Dijkstra`s Algorithm - Stuck in an infinite loop
  • Should I throw IllegalArgmentException when 'user of given id not exist'?
  • In Nimbus, how to paint TextField when MouseOver?
  • why won't checkforWin(File f) return true when it is true?
  • Android: Cursor is always returning null even if the database is not empty
  • Repeating for loop in menu
  • Can Java garbage collector randomly delete objects in the On-Heap tier?
  • Apache CXF Exception: SSL connection unexpectedly closed
  • Add properties to ArrayList<Object> in Java
  • Multiple Adapters or One Adapter for different lists and objects - Code Performance
  • Is it good practice in Java for a class's method to redundantly return a modified global field of the class?
  • How to change the color of the background in libgdx labels?
  • direct file path not working
  • ClassFileTransformer + Javassist: no such field
  • How do I change and instance variable for an object which the user selects from a combobox?
  • reading and updating a large xml file in java
  • ActionListener and Thread.sleep
  • What is the maximum of number of arguments for varargs in java?
  • When I compile I get an error as "ask" cannot be resolved or is not a field"
  • What is the best way to check if 4 integer variables are equal to 0?
  • Storing constant webdriver elements in an enum
  • Java: Why main class does not extend Thread class
  • Java - how to find out if a directory is being used by another process?
  • How can I get a method to print?
  • Java unknown exceptions
  • BufferedReader,StreamWriter crash
  • found raw type: JComboBox
  • Java Generics -> Function return type
  • how to refresh contents of jtable on event of action listener?
  • Why does List interface extend Collection interface?
  • Pros and Cons of Clojure http client libraries
  • use final inside a for each loop
  • Convert java data object to service object
  • Unsupported major.minor version 51.0 while executing JSP
  • How do I display a word diagonally in Java?
  • making sure one task completes before another starts in java
  • My program gives an index out of bounds error
  • Removing duplicate characters in a String (user inputted keyword)
  • Jersey 2.0 Content-Length not set
  • AWS.SimpleQueueService.NonExistentQueue Exception thrown when Accessing Existing SQS queue
  • Where can I find the source code for the com.sun.jdi package?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org