繁体   English   中英

Java 将值插入到 MongoDB 中的数组

[英]Java insert value to Array in MongoDB

我是 MongoDB 的新手,完全被查询弄糊涂了。 我只需要通过将字符串值(例如:温度)添加到字符串列表来更新 mongodb 数据库中的文档。 从研究中我知道我必须为此使用 $push 方法。 我认为代码必须看起来像这样:

BasicDBObject newDocument = new BasicDBObject().append("$set", 
new BasicDBObject().append("Subscribed Topics", topic));

collection.update(new BasicDBObject().append("Sensor Type", sensorType), newDocument);
new BasicDBObject("$push",
new BasicDBObject("Subscribed Topics", topic));

带有数组的字段称为“订阅主题”,“主题”是一个字符串(温度)。 然后我想用相应的“传感器类型”更新集合中的文档。 但是,我真的不知道如何正确调用 $push 部分。 我希望有人能帮我整理这部分代码。

最好的问候。

更新,我尝试按照重复问题中的建议实施,但仍然出错。 非常不确定这是否是正确的方法。

 DBObject listItem = new BasicDBObject("Subscribed Topics", "Light");
             DBObject updateQuery = new BasicDBObject("$push", listItem);
             collection.update(query, updateQuery);`

我为关键订阅主题(数组)创建了一个值为 Light in 的新对象。 为什么我把它推送到一个新的对象呢?

我的天啊! 这个问题让我再次陷入早已被遗忘的 Java 世界 - 经过这么多年...... ;) Anyhoo,这是一个完整的工作示例,它可能会给你一个关于正在发生的事情的线索。 您可以多次运行代码,看看“订阅主题”数组中的元素数量是如何增加的。

我使用了以下驱动程序: https : //oss.sonatype.org/content/repositories/releases/org/mongodb/mongo-java-driver/3.3.0/mongo-java-driver-3.3.0.jar

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;

import org.bson.Document;
import org.bson.conversions.Bson;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class MongoDbPush {
  public static void main(String[] args)
  {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("pushExampleDb");
    MongoCollection<Document> collection = database.getCollection("pushExampleCollection");

    String sensorType = "Temperature";

    // try to load existing document from MongoDB
    Document document = collection.find(eq("Sensor Type", sensorType)).first();
    if(document == null)
    {
      // no test document, let's create one!
      document = new Document("Sensor Type", sensorType);

      // insert it into MongoDB
      collection.insertOne(document);

      // read it back from MongoDB
      document = collection.find(eq("Sensor Type", sensorType)).first();
    }

    // see what it looks like in JSON (on the first run you will notice that it has got an "_id" but no "Subscribed Topics" array yet)
    System.out.println(document.toJson());

    // update the document by adding an entry to the "Subscribed Topics" array
    Bson filter = eq("Sensor Type", sensorType);
    Bson change = push("Subscribed Topics", "Some Topic");
    collection.updateOne(filter, change);

    // read one more time from MongoDB
    document = collection.find(eq("Sensor Type", sensorType)).first();

    // see what the document looks like in JSON (on the first run you will notice that the "Subscribed Topics" array has been created and has got one element in it)
    System.out.println(document.toJson());

    mongoClient.close();
  }
}

上述方法仍然有效,但是,使用更新的 Mongo 驱动程序,以下也是一种可行的机制。

以下适用于 Mongo Driver 3.6 以上(在本例中使用 3.12.4)

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("pushExampleDb");
MongoCollection<Document> collection = database.getCollection("pushExampleCollection");

collection.findOneAndUpdate(Filters.eq("Sensor Type",<theSensorTypeNameComesHere>), 
                            Updates.pushEach("Subscribed Topics",<listContainingTheValuesComeHere>));

参考:$push$each来自 MongoDB 手册

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM