我一直在玩弄Perl MongoDB库,并且一直在努力弄清楚如何做一些非常简单的事情。
如何在插入时保持数据字段的顺序?我的代码如下:
use MongoDB;
use MongoDB::Database;
use MongoDB::OID;
my $conn = MongoDB::Connection->new;
my $db = $conn->test;
my $users = $db->testlogwiki;
$users->insert
(
{
"product" => "WooHoo",
"errcode" => "WM2001_89873",
"solution1" => "Hit the computer.",
"line_text" => "Inserted in Perl too"
}
);
当我返回并在MongoDB中查找记录的插入方式时,它看起来像这样:
db.testlogwiki.find([criteria that find it]).pretty();
"_id" : ObjectId("4fc62c2900ece6040c000000"),
"solution1" : "Hit the computer.",
"product" : "WooHoo",
"errcode" : "WM2001_89873",
"line_text" : "Inserted in Perl too"
这不是我想要的顺序...我如何使它成为我想要的订单?
Perl 和 Mongo 的 BSON 哈希值都是无序的。如果您需要以某种方式订购属性,则必须自己跟踪它。
MongoDB 不一定与此有任何关系 - Perl 哈希首先不会保留顺序:
$ perl -MData::Dumper -E 'my $foo = { one => 1, two => 2, three => 3 }; print Dumper($foo);'
$VAR1 = {
'three' => 3,
'one' => 1,
'two' => 2
};
您可以使用 Tie::IxHash 创建哈希,这些哈希将保留它们在内存中的顺序,但我不能说它是否也会使它们在插入和检索 MongoDB 时保留它们的顺序。