MongoDB:在单个更新中$ push多个对象和$ pop多个对象 [英] MongoDB: $push Multiple Objects, and $pop Multiple Objects in Single Update

查看:322
本文介绍了MongoDB:在单个更新中$ push多个对象和$ pop多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下一个包含100个对象的数组的MongoDB文档.我们希望将数组长度固定保持在100.当一批新对象到达时(可能是1、5、10等),我们想用新对象更新数组,同时删除等量的旧对象,以便数组长度保持固定.我选择将数组从MongoDB中读取到我的应用程序中,进行一些修改,然后使用$set来更新该数组:

Imagine a MongoDB document with an array of 100 objects. And we want to keep the array length fixed at 100. When a batch of new objects arrives (could be 1, 5, 10, etc.), we want to update the array with new objects, while removing an equal amount of old objects so the array length will stay fixed. I've opted to reading the array from MongoDB into my app, making some modifications, then using $set to update the array:

var newData = [
  { ... },
  { ... },
  { ... },
  { ... },
  { ... }
];
var oldData = Collection.findOne({exchange: 'The Exchange', market: 'The Market'}).data;
newData = newData.concat(oldData).slice(0, 100);
Collection.update(
  {
    exchange: 'The Exchange',
    market: 'The Market'
  },
  {
    $set: {
      data: newData
    }
  }

在MongoDB中是否有可能将新版本$push放在前面,而同时使用$pop从后面删除等量的对象?

Is it possible in MongoDB to $push the new on to the front, while simultaneously using $pop to remove an equal amount of objects off the back?

推荐答案

好吧,答案是是"和否".您不能同时执行 $push $pull 操作在单个更新中的同一阵列上.对于操作的相同路径",这是不允许的,因为在当前更新语法中,$push$pull均未真正确定以任何顺序发生.

Well the answer is both "yes" and "no" to put it in slightly confusing terms. What you cannot do is both $push and $pull operations on the same array in a singular update. This is not allowed for the "same path" of operations because neither $push or $pull is really determined to occur in any order within the current update syntax.

但是,在您的特定情况下,这不是您要的内容.做您想做的事,MongoDB支持 $slice > 修饰符,可以与 $each .当新项目添加到数组时,这将有效地限制"数组的总大小.

However in your specific context, that is not what you are asking. To do what you want, MongoDB supports the $slice modifier which can be used along with $each. This will effectively "limit" the total size of the array as new items are added to it.

按照您的示例:

Collection.update(
    { "exchange": "The Exchange", "market": "The Market" },
    { "$push": { "data": { "$each": newData, "$slice": 100 } } }
)

这实际上将数组的大小限制为第一个100成员,同时向其中添加了新项目.

That effectively limits the size of the array to the first 100 members whilst adding the new items to it.

请注意,尽管流星实现的客户端版本的"minimongo"可能不支持此功能.但是,您可以做的是在服务器上执行此操作,然后通过发布来公开该方法.有很多示例向您展示如何使用发布.

Take note though that this may not be supported in the client version of "minimongo" as implemented by meteor. What you can do though is execute this on the server, and expose the method via publish. There are plenty of examples to show you how to use publish.

这篇关于MongoDB:在单个更新中$ push多个对象和$ pop多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆