[英]How to get some documents of array in MongoDB
I have collection "users" where username , password,questions are stored . 我有集合“用户”,其中存储了用户名,密码和问题。 "questions" is an array of documents . “问题”是一系列文件。 I would like to get all users with some questions ie username , password and an array of questions (some part) How can i do that from console or java ? 我想让所有用户遇到一些问题,即用户名,密码和一系列问题(某些部分),我该如何从控制台或Java做到这一点?
Here i want to get username , password and first document of questions which is {question:"dawdaw",answered:0} 在这里,我想获取用户名,密码和第一个问题文档,即{question:“ dawdaw”,answered:0}
You can use slice like this 你可以像这样使用切片
db.users.find({},{"questions":{$slice:1}})
Hope it will help 希望对你有帮助
Use $elemMatch
projection to get the desired result. 使用$elemMatch
投影可获得所需的结果。 The following find()
operation queries for all documents where the $elemMatch
projection returns only the first matching element of the questions
array where the question
field has a value of "dawdaw"
and answered
has 0
value: 以下find()
操作查询所有文档,其中$elemMatch
投影仅返回questions
数组的第一个匹配元素,其中question
字段的值为"dawdaw"
并且answered
值为0
:
db.users.find({},
{
"username": 1, "password": 1,
"questions": {
"$elemMatch": {
"question" : "dawdaw",
"answered" : 0
}
}
}
);
From the sample given, the operation returns the following document: 从给出的样本中,该操作返回以下文档:
/* 0 */
{
"_id" : ObjectId("561a84ffaa233b38d803509a"),
"username" : "asd@mail.ru",
"password" : "asd",
"questions" : [
{
"question" : "dawdaw",
"answered" : 0
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.