查找和放大器;从数组中返回第一个匹配的子文档(流星/蒙戈) [英] Find & return first matching subdocument from array (Meteor / Mongo)
问题描述
如何找到和'任务'阵列匹配完成返回第一个子文档:真正的
使用 findOne
返回整个文档..有另一个函数返回一个子文档?
{
标题:awebsite.com
公司:公司
companyID:Random.id()
类别:'网站'
主演:假的
时间表:{
任务: [
{
名称:'独立写作
完成:真
待办事项:
{TODO:'东西',完成了:假的,todoID:Random.id()}
{TODO:'东西',完成了:假的,todoID:Random.id()}
{TODO:'东西',完成了:假的,todoID:Random.id()}
]
}
{
名称:'TASK2
完成:假的
待办事项:
{TODO:'东西',完成了:假的,todoID:Random.id()}
{TODO:'东西',完成了:假的,todoID:Random.id()}
{TODO:'东西',完成了:假的,todoID:Random.id()}
]
}
]
}
}
您可以通过的聚集 在那里你可以采取指数和限用的 $匹配
管道。使用 $开卷
运算符来解构你的任务数组的文件流,然后可以匹配。因为你想只返回的任务数组中的第一子文档匹配完成:真正的,你可以使用的 $上限
运营商在过去的流水线阶段返回只有一个子文档:
db.collection.aggregate([
{
$匹配:{
timeline.tasks.completed:真
}
},
{
$放松:$ timeline.tasks
},
{
$匹配:{
timeline.tasks.completed:真
}
},
{
$组:{
_ID: {
任务:$ timeline.tasks
}
}
},
{
$项目:{
_id:0,
任务:$ _id.tasks
}
},
{
$限制:1
}
])
结果:
{
结果:
{
任务 : {
名:独立写作
已完成:真实,
待办事项:[
{
做某事,
已完成:假的,
todoID:jfoe84jn
},
{
做某事,
已完成:假的,
todoID:yr934hjs
},
{
做某事,
已完成:假的,
todoID:84hdkl0t
}
]
}
}
]
确定:1
}
how do I find and return the first subdocument in the 'tasks' array that matches completed: true?
using findOne
returns the entire document.. is there another function for returning a subdocument?
{
title: 'awebsite.com'
company: 'a company'
companyID: Random.id()
category: 'website'
starred: false
timeline: {
tasks: [
{
name: 'task1'
completed: true
todos: [
{todo: 'something', completed: false, todoID: Random.id()}
{todo: 'something', completed: false, todoID: Random.id()}
{todo: 'something', completed: false, todoID: Random.id()}
]
}
{
name: 'task2'
completed: false
todos: [
{todo: 'something', completed: false, todoID: Random.id()}
{todo: 'something', completed: false, todoID: Random.id()}
{todo: 'something', completed: false, todoID: Random.id()}
]
}
]
}
}
You can do this by aggregation where you can take advantage of an index and limit with the $match
pipeline. Use the $unwind
operator to deconstruct your tasks array into a stream of documents that can then be matched. since you would want to return only "the first subdocument in the 'tasks' array that matches completed: true", you could use the $limit
operator in the last pipeline stage to return only one subdocument:
db.collection.aggregate([
{
$match: {
"timeline.tasks.completed": true
}
},
{
$unwind: "$timeline.tasks"
},
{
$match: {
"timeline.tasks.completed": true
}
},
{
$group: {
_id: {
"tasks": "$timeline.tasks"
}
}
},
{
$project: {
_id: 0,
tasks: "$_id.tasks"
}
},
{
$limit: 1
}
])
Results in:
{
"result" : [
{
"tasks" : {
"name" : "task1",
"completed" : true,
"todos" : [
{
"todo" : "something",
"completed" : false,
"todoID" : "jfoe84jn"
},
{
"todo" : "something",
"completed" : false,
"todoID" : "yr934hjs"
},
{
"todo" : "something",
"completed" : false,
"todoID" : "84hdkl0t"
}
]
}
}
],
"ok" : 1
}
这篇关于查找和放大器;从数组中返回第一个匹配的子文档(流星/蒙戈)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!