Mongo数组更新或推入一个查询 [英] Mongo array update or push in one query

查看:82
本文介绍了Mongo数组更新或推入一个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们的mongo集合包含以下形状的文档:

Let's assume we have mongo collection containing documents of the following shape:

 {
   _id: '1234',
   letters: ['a', 'b', 'c', 'd'],
 }

,但有时 letters 字段可能为 null .

我想知道是否可以在单个查询中实现以下目标

  • 如果 letters 数组不为空,则将第一项设置为"x".
  • 否则,将 letters 字段设置为 ['x'] .
  • If letters array is non empty, set the first item to 'x'.
  • Otherwise, set letters field to ['x'].

当然,最简单的想法行不通

Of course, the simplest possible idea does not work

db.collection.update({_id: '...'}, {$set:{'letters.0':'x'}});

因为如果尚未设置 letters 字段,则上述操作的结果将为:

because if the letters field was not yet set the result of the above operation will be:

{
  // ...
  letters: {
    '0': 'x'
  }
}

有没有办法告诉mongo我的意图是创建一个数组,而不是对象?

Is there some way to tell mongo that my intention is to create an array, not an object?

推荐答案

您可以使用 $ addToSet ,如果您关心阵列上的重复项.

You can use the $push operator, or the $addToSet if you care for duplicates on the array.

您的查询将如下所示:

db.collection.update({_id: '...'}, {$push:{'letters':'x'}});
db.collection.update({_id: '...'}, {$addToSet:{'letters':'x'}});

这篇关于Mongo数组更新或推入一个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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