向现有的 mongo 数组添加新值 [英] Adding new values to existing mongo array

查看:84
本文介绍了向现有的 mongo 数组添加新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例 Mongo 文档是:

My sample Mongo doc is:

{
    "_id" : ObjectId("51fa3d516bde1ca6f017a570"),
    "digits":[
        0,
        1,
        2,
        3,
        4,
        5,
        6
    ]
}

我想用一些额外的值附加数字数组.说:

I want to append digits array with some extra values. say:

int[] myIntArray = new int[3];
int[] myIntArray = {7,8,9};

如何在java中将myIntArray附加到数字数组我的java代码是:

How to append myIntArray to digits array in java my java code is:

BasicDBList digits=(BasicDBList) cursor.next().get("digits");

推荐答案

MongoDB 有 $push 运算符.您不必遍历集合来执行此操作,您可以在数据库内部进行更新.

MongoDB has the $push operator for that. You don't have to iterate over the collection to do it, you can do an update inside the database.

用Java编写,看起来像

Written in Java, this would look something like

collection.update(...query expression...,
  new BasicDBObject("$push",
    new BasicDBObject("digits", value)));

这假定 value 是数组的单个新值.如果您想一次附加数组的所有元素,您必须使用 $each 修饰符(有关详细信息,请参见上面的链接).

This assumes that value is a single new value for the array. If you want to append all the elements of an array at once, you have to use the $each modifier (see above link for the details).

这篇关于向现有的 mongo 数组添加新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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