下面介绍:$push $pushAll $addToSet关键字执行update操作
一、$push关键字的用法
public static void testUpdate5(){
String ip = "192.168.2.3";
int port = 27017;
String[] citys = {"beijing","tianjing","wuhan"};
MongoClient client = MongoDBUtil.getClient(ip, port);
DB db = client.getDB("zhanglong_test");
DBCollection collection = db.getCollection("students");
BasicDBObject query = new BasicDBObject("name", "jacky");
//因为$push关键字只能对数组进行操作,所以先添加一个key为city的数组
collection.update(query, new BasicDBObject().append("$set",new BasicDBObject("city",citys)));
/*
* $push关键字的说明:它只能操作一个数组
* 1.如果指定的键是数组增追加新的数值
* 2.如果指定的键不是数组则中断当前操作Cannot apply $push/$pushAll modifier to non-array
* 3.如果不存在指定的键则创建数组类型的键值对
*/
//在key中添加一个城市:dalian
collection.update(query, new BasicDBObject().append("$push",new BasicDBObject("city","dalian")));
}
可以看到在city数组中,多了一个dalian值。
二、$pushAll关键字的用法:
public static void testUpdate6(){
String ip = "192.168.2.3";
int port = 27017;
String[] city2 = {"xiaogan","hanchuan"};
MongoClient client = MongoDBUtil.getClient(ip, port);
DB db = client.getDB("zhanglong_test");
DBCollection collection = db.getCollection("students");
BasicDBObject query = new BasicDBObject("name", "jacky");
/*
* $pushAll关键字的说明:它也只能操作一个数组
* 它的用法和$push差不多,只不过是向数组中添加一组数据而已
*/
//在key中添加一个城市:dalian
collection.update(query, new BasicDBObject().append("$pushAll",new BasicDBObject("city",city2)));
}
可以看到name为jacky的文档 city数组中多了两个值,分别为xiaogan,hanchuan
三、$addToSet关键字的用法:
目标数组存在此项则不操作,不存在此项则加进去
public static void testUpdate7(){
String ip = "192.168.2.3";
int port = 27017;
String[] city2 = {"xiaogan","hanchuan"};
MongoClient client = MongoDBUtil.getClient(ip, port);
DB db = client.getDB("zhanglong_test");
DBCollection collection = db.getCollection("students");
BasicDBObject query = new BasicDBObject("name", "jacky");
//因为原来city中存在wuhan,所以添加不进去
collection.update(query, new BasicDBObject().append("$addToSet",new BasicDBObject("city","wuhan")));
//原来city中不存在huangshi,所以添加进去了
collection.update(query, new BasicDBObject().append("$addToSet",new BasicDBObject("city","huangshi")));
}
查看数据库:
可以看到多了一个huangshi的值,但是wuhan没有添加进去!