作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想插入这种类型的模型:
{
_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/
我是一名优秀的程序员,十分优秀!