gpt4 book ai didi

java - 如何在MongoDB JAVA中向对象追加数据并在一页上显示其内容?

转载 作者:行者123 更新时间:2023-12-02 12:02:10 25 4
gpt4 key购买 nike

我想插入这种类型的模型:

{
_id: POST_ID
title: TITLE_OF_POST,
by: POST_BY,
questions: [
{
QID:1,
Question:"text"
},
{
QID:1,
Question:"text"
}
]
}

我想使用

对上述情况进行建模
Document document=new Document("topic",topic)
.append("empid",empid)
.append("teacher", teacher)
.append("date",d)
.append("questions",[
for (int i = 0; i < questions.length; i++) {//This is not correct.
String string = questions[i];}]);

我想在对象名称问题中插入问题,然后使用 qid 上的 for 循环将它们显示在一页上,然后使用 servlet out.println 在一页上显示所有问题。我想选择文档,然后迭代 qid 并显示所有问题。

示例:

Title of Assignment \n
Teacher Name \n
Question 1: Content of question 1. \n
Question 2: Content of Question 2.

最佳答案

为了创建Document实例,您使用了绝对错误的Java语法。在 Java 中你不能使用类似的东西:

.append("questions",[  for (int i = 0; i < questions.length; i++) 

您应该首先创建问题列表,然后在准备文档实例时使用此列表:

List<Map<String, Object>> questions = new ArrayList<>();
questions.add(new HashMap<String, Object>(){{
put("QID", 1);
put("Question", "text");
}});
questions.add(new HashMap<String, Object>(){{
put("QID", 2);
put("Question", "text");
}});


Document document = new Document("_id", 1001)
.append("topic", "topic")
.append("empid", 5)
.append("teacher", "teacher")
.append("date", 555)
.append("questions", questions);

collection.insertOne(document);

要从集合中检索以前插入的项目,您可以使用以下命令:

    Document foundDocument = collection.find(new Document("_id", 1001)).first();
List<Map> foundQuestions = (List) foundDocument.get("questions");
for (Map foundQuestion: foundQuestions) {
Integer qid = (Integer) foundQuestion.get("QID");
String questionValue = foundQuestion.get("Question").toString();
System.out.println(qid + " : " + questionValue);
}

关于java - 如何在MongoDB JAVA中向对象追加数据并在一页上显示其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47164872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com