[英]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:在您的情况下,我建议遵循以下逻辑:
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.