我对 mongodump 生成的 .bson 二进制文件非常好奇。 一开始我的猜测是 BSON Array
Bson::Array(array_of_documents)
然后:
#Cargo.toml
[dependecies]
...
bson = "2.1.0"
//main.rs
fn main()
{
let mut path=std::env::current_dir().unwrap();
path.push("backup/transactions.bson");
if path.exists() {
match std::fs::File::open(&path)
{
Err(err)=>panic!("Failed to open '{}'",path.to_str().unwrap(),err),
Ok(file)=>{
if let Ok(bson_file)=bson::Bson::from_reader(&file) {
if let Some(bson_array)=bson_file.as_array() {
for bson_data in bson_array {
println!("BSON Data: {:?}",&bson_data);
}
} else {
println!("Not an array");
}
} else {
println!("Not a BSON file");
}
}
}
}
}
然后我就跑了:
$ cargo run
...
Not an array
显然是一个 BSON 文件,但不是数组!那时是什么? 🤔
然后我想..如果它是一个文档呢
Bson::Document(bson_data)
?
//main.rs
fn main()
{
let mut path=std::env::current_dir().unwrap();
path.push("backup/transactions.bson");
if path.exists() {
match std::fs::File::open(&path)
{
Err(err)=>panic!("Failed to open '{}'",path.to_str().unwrap(),err),
Ok(mut file)=>{
if let Ok(doc_data)=bson::Document::from_reader(&mut file) {
//Print all keys of the document
println!("Document keys: {:?}",doc_data.keys().map(|x| x.as_str()).collect::<Vec<&str>>());
} else {
println!("Not a document");
}
}
}
}
}
$ cargo run
...
["_id","code","type","customerName","items","createdAt"]
这些密钥是我的交易数据! 😮 但它只检索一份文档并打印该文档的所有键。其余的文件在哪里?我在 .bson 文件中转储了 50 多个文档。 然后我怀疑一些事情,如果.. .bson 文件由一系列文件组成,并放置在另一个文件旁边。
//main.rs
fn main()
{
let mut path=std::env::current_dir().unwrap();
path.push("backup/transactions.bson");
if path.exists() {
match std::fs::File::open(&path)
{
Err(err)=>panic!("Failed to open '{}'",path.to_str().unwrap(),err),
Ok(mut file)=>{
//Read file size
let n=file.seek(std::io::SeekFrom::End(0)).unwrap_or(0);
//Put file pointer at the beginning of file
if file.seek(std::io::SeekFrom::Start(0)).is_ok() {
//Hold the number of retrieved documents
let mut i=0_u16;
//Read only 50 documents or end of file has been reached
while i < 50 && file.stream_position().unwrap_or(0) < n {
if let Ok(doc_data) = bson::Document::from_reader(&mut file) {
println!("Document: {}. {:?}",i+1,&doc_data);
i+=1;
}
}
}
}
}
}
}
$ cargo run
...
Document: 1. Document({"_id": ObjectId("63ee1b8b4b7c65e95ba891bd"), "originalId": ObjectId("6252fab17b201412088a4aaa"), "client": ObjectId("63d62de44370c4d5f1670f78"), "type": String("room"),...
...
Document: 36. Document({"_id": ObjectId("63ee1b8b4b7c65e95ba891e7"), "originalId": ObjectId("625300cb7b201412088a4d30"), "client": ObjectId("63d62de44370c4d5f1670f78"),...
是的..我的猜测是对的。 .bson 文件是一系列
Bson::Document(data)
放置在另一个旁边