如何在 MongoDB 中获取数组的一些文档
How to get some documents of array in MongoDB
我有一个集合 "users",其中存储了用户名、密码、问题。 "questions" 是一个文档数组。我想让所有用户提出一些问题,即用户名、密码和一系列问题(某些部分)我如何从控制台或 java 做到这一点?
我想在这里获取用户名、密码和第一个问题文档,即{question:"dawdaw",answered:0}
你可以像这样使用 slice
db.users.find({},{"questions":{$slice:1}})
希望对您有所帮助
仅使用 $elemMatch
projection to get the desired result. The following find()
operation queries for all documents where the $elemMatch
投影 returns 仅 questions
数组的第一个匹配元素,其中 question
字段具有"dawdaw"
和 answered
的值有 0
值:
db.users.find({},
{
"username": 1, "password": 1,
"questions": {
"$elemMatch": {
"question" : "dawdaw",
"answered" : 0
}
}
}
);
从给出的样本中,运行returns以下文件:
/* 0 */
{
"_id" : ObjectId("561a84ffaa233b38d803509a"),
"username" : "asd@mail.ru",
"password" : "asd",
"questions" : [
{
"question" : "dawdaw",
"answered" : 0
}
]
}
我有一个集合 "users",其中存储了用户名、密码、问题。 "questions" 是一个文档数组。我想让所有用户提出一些问题,即用户名、密码和一系列问题(某些部分)我如何从控制台或 java 做到这一点?
我想在这里获取用户名、密码和第一个问题文档,即{question:"dawdaw",answered:0}
你可以像这样使用 slice
db.users.find({},{"questions":{$slice:1}})
希望对您有所帮助
仅使用 $elemMatch
projection to get the desired result. The following find()
operation queries for all documents where the $elemMatch
投影 returns 仅 questions
数组的第一个匹配元素,其中 question
字段具有"dawdaw"
和 answered
的值有 0
值:
db.users.find({},
{
"username": 1, "password": 1,
"questions": {
"$elemMatch": {
"question" : "dawdaw",
"answered" : 0
}
}
}
);
从给出的样本中,运行returns以下文件:
/* 0 */
{
"_id" : ObjectId("561a84ffaa233b38d803509a"),
"username" : "asd@mail.ru",
"password" : "asd",
"questions" : [
{
"question" : "dawdaw",
"answered" : 0
}
]
}