在我的mongodb数据库中,有一个'messages'集合,它有一个字段'order',它的值为整数
msg1.order=1, msg2.order=2, msg3.order=3, msg4.order=4, msg5.order=5, ...
每条消息的表示消息子集的有序序列。
同时,可以使用jquery.sortable通过网页重新排序这些消息。例如,如果我将位置No.3上的消息移动到No.1,那么我应该将'order'值更改为
msg1.order=2, msg2.order=3, msg3.order=1, msg4.order=4, msg5.order=5, ...
。是否有任何mongodb修饰符或其他方法进行此类更新,以便我可以一步或安全地进行此类更新?
3份样本文件:
{
"author_id": "a",
"class": "principle",
"content_id": null,
"host_id": null,
"modified_date": 1330935540,
"order": 1,
"pub_date": 1330935540,
"score": 0,
"text": "Hello World!",
"vote_down_count": 0,
"vote_up_count": 0
}
{
"author_id": "a",
"class": "principle",
"content_id": null,
"host_id": null,
"modified_date": 1330935538,
"order": 2,
"pub_date": 1330935538,
"score": 0,
"text": "Nice to meet you.",
"vote_down_count": 0,
"vote_up_count": 0
}
{
"author_id": "a",
"class": "principle",
"content_id": null,
"host_id": null,
"modified_date": 1330935548,
"order": 3,
"pub_date": 1330935548,
"score": 0,
"text": "Great!",
"vote_down_count": 0,
"vote_up_count": 0
}
答案 0 :(得分:0)
为了原子地执行此操作,您的所有三个示例文档都需要成为同一文档的一部分。 MongoDB只对简单文档进行原子操作:http://www.mongodb.org/display/DOCS/Atomic+Operations
如果它们是单个文档的一部分,则以下内容将更改第2和第3个子文档的顺序:
> db.so.find().pretty(); { "_id" : ObjectId("4f55e7ba362e2f2a734c92f8"), "subs" : [ { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935540, "order" : 1, "pub_date" : 1330935540, "score" : 0, "text" : "Hello World!", "vote_down_count" : 0, "vote_up_count" : 0 }, { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935538, "order" : 2, "pub_date" : 1330935538, "score" : 0, "text" : "Nice to meet you.", "vote_down_count" : 0, "vote_up_count" : 0 }, { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935548, "order" : 3, "pub_date" : 1330935548, "score" : 0, "text" : "Great!", "vote_down_count" : 0, "vote_up_count" : 0 } ] }
查询:
db.so.update( { _id: new ObjectId("4f55e7ba362e2f2a734c92f8")}, { $set : { 'subs.1.order' : 3, 'subs.2.order' : 2 } } );
结果:
> db.so.find().pretty(); { "_id" : ObjectId("4f55e7ba362e2f2a734c92f8"), "subs" : [ { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935540, "order" : 1, "pub_date" : 1330935540, "score" : 0, "text" : "Hello World!", "vote_down_count" : 0, "vote_up_count" : 0 }, { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935538, "order" : 3, "pub_date" : 1330935538, "score" : 0, "text" : "Nice to meet you.", "vote_down_count" : 0, "vote_up_count" : 0 }, { "author_id" : "a", "class" : "principle", "content_id" : null, "host_id" : null, "modified_date" : 1330935548, "order" : 2, "pub_date" : 1330935548, "score" : 0, "text" : "Great!", "vote_down_count" : 0, "vote_up_count" : 0 } ] }