不按字母顺序更新MongoDB中的文档

时间:2014-01-08 06:53:22

标签: c mongodb

我正在MongoDB上创建一个项目并插入一些文档,现在我正在通过此代码更新文档。

bson_init( query );

bson_append_string(query, "First", "A");
bson_append_string(query, "Second", "B");
bson_append_string(query, "Third", "C");
bson_append_string(query, "Fourth", "D");
bson_append_string(query, "Fifth", "E");

bson_finish(query );


bson_init( b );
bson_append_start_object(b,"$set");

if(checkBox_First->isChecked() == true)
bson_append_string( b, "First", "Z");

if(checkBox_Second->isChecked() == true)
bson_append_string( b, "Second", "X");

if(checkBox_Third->isChecked() == true)
bson_append_string( b, "Third", "R");

if(checkBox_Fourth->isChecked() == true)
bson_append_string( b, "Fourth", "Y");

if(checkBox_Fifth->isChecked() == true)
bson_append_string( b, "Fifth","P");

bson_append_finish_object( b );

bson_finish(b );

mongo_update(conn,TEST_NS,query,b,MONGO_UPDATE_BASIC,0);
bson_destroy(query);
bson_destroy(b);

代码工作正常但更新后,文档按字母顺序存储。任何人都可以告诉我如何更新文档而不按字母顺序排序。我正在使用"$set"更新参数。我正在使用C Driver。

1 个答案:

答案 0 :(得分:0)

确保顶级字段顺序符合您的要求的唯一方法是立即设置整个文档。如果您已经在文档中有某些字段,$set运算符无法指定文档中您希望添加新字段的位置。

从下一个版本(2.6,当前可用作不稳定开发版本2.5.x)开始,此行为将发生更改,并且文档中的字段不会重新排序。根据您部署应用程序的时间,您可以尝试开发版本,并且在使用该版本部署2.6之后。

请注意,通常顶级字段顺序无关紧要,通常无法保证。