简体   繁体   English

Mongodb:如何在一次操作中更新一些元素并删除数组的其余部分?

[英]Mongodb: how to update some elements and remove the rests of an array in an single operation?

To an array I want to update some elements and keep array's size no great than N. How to do it in an single operation?对于一个数组,我想更新一些元素并保持数组的大小不大于 N。如何在单个操作中完成? Lets' make an example to make my question clear:让我们举个例子来说明我的问题:

1)db.test.insertOne({a:[1, 100, 3, 5, 600]});
{ 
    "_id" : ObjectId("5fc5a14e1b800790b21afa65"), 
    "a" : [
        1.0, 
        100.0, 
        3.0, 
        5.0, 
        600.0
    ]
}
2) change it to
{ 
    "_id" : ObjectId("5fc5a14e1b800790b21afa65"), 
    "a" : [
        1.0, 
        100.0, 
        5.0
    ]
}

As shown above, a[2]->5, and N=3, only keeps a[0],a[1],a[2].如上图,a[2]->5,且N=3,只保留a[0],a[1],a[2]。 I have to make these happen in one single operation to make data consistent(don't consider multiple clients) How could I do?我必须在一次操作中完成这些操作以使数据保持一致(不要考虑多个客户端)我该怎么办? Thanks!谢谢!

In your case, I'd recommend to follow this logic:在您的情况下,我建议遵循以下逻辑:

  1. If the array in the memory has not been changed - do nothing.如果 memory 中的数组未更改 - 什么也不做。
  2. If your array was changed and it's small then just update the whole array.如果您的数组已更改并且它很小,那么只需更新整个数组。
  3. If your array was changed only a little bit and it's pretty big then calculate in your app what exactly elements were changed and create an update with corresponding operations for everyone (remove, update, insert).如果您的数组仅更改了一点并且它非常大,那么在您的应用程序中计算确切的元素更改并为每个人创建具有相应操作的更新(删除、更新、插入)。 Be careful, it's an error-prone approach.小心,这是一种容易出错的方法。

If your app runs into case number 3 "often", it means you designed a wrong data structure to solve your problem.如果您的应用程序“经常”遇到第 3 种情况,则意味着您设计了错误的数据结构来解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM