使用Java将数据插入mongodb

使用Java将数据插入mongodb

我正在尝试使用Java将数据插入MongoDB,但是在尝试编译代码时出现错误。我不知道是什么原因引起的错误。我想添加一个新书条目。



error message:
 required: String,Object
  found: List<Document>
  reason: actual and formal argument lists differ in length
UseMongoDB.java:61: error: method put in class Document cannot be applied to given types;
book.put(publishers);







private MongoCollection<Document> books = db.getCollection("books");

	void insertanewbook() {


		Document book = new Document();
		book.put("title", "test");
	      	book.put("category","test");
                book.put("price",12.3);

                List<Document> authors = new ArrayList<Document>();
		Document author = new Document();
                author.put("first_name","jonn");
                author.put("last_name","james");
                author.put("country","t");
                author.put("website","www.test.com");
		authors.add(author);
		book.put(authors);

		List<Document> publishers = new ArrayList<Document>();
		Document publisher = new Document();
                publisher.put("publish_date",new Date());
                publisher.put("name","test");
                publisher.put("country","test");
		publisher.put("website","www.test.com");
		publishers.add(publisher);
		book.put(publishers);

		books.insertOne(book);

	}

最佳答案

从您发布的错误消息中...

reason: actual and formal argument lists differ in length


换句话说,方法put需要两个参数,而您仅提供了一个。从您发布的代码中,您丢失了对方法put()的调用中的键。只需添加相关密钥,例如

book.put("publishers", publishers);

08-26 09:31