【发布时间】:2012-07-27 15:24:36
【问题描述】:
我无法用语言准确地描述我的想法,所以这里有一个例子:
[
{
'description': 'fruits',
'examples': [
{
'name': 'Apple',
'color': ['red', 'green']
},
{
'name': 'Banana',
'color': 'yellow'
}
]
},
{
'description': 'vegetables',
'examples': [
{
'name': 'Tomato',
'color': 'red'
},
{
'name': 'Carrot',
'color': 'orange'
}
]
},
{
'description': 'Wweets',
'examples': [
{
'name': 'Chocolate',
'color': ['brown', 'black', 'white']
},
{
'name': 'Candy',
'color': 'various'
}
]
}
]
让我们一步一步来:
如果我想查看所有食物类别,我通过以下命令查询
db.food.find()
我想看看蔬菜
db.food.find({ 'description': 'vegetables' })
现在假设我忘记了胡萝卜的样子(笑)。我该怎么办?我尝试了以下(本机 node.js MongoDB 驱动程序):
collection.find({'examples.name': 'Carrot'}, function(err, example){
console.log(example)
// It still returns me the whole object!
});
因此,我希望 MongoDB 返回对象的下一个最高实例。例如,我想这样做。
console.log(example.color)
// 'orange'
你有什么想法吗?我是面向文档的数据库的新手:/
【问题讨论】:
-
嘿,通过查找,您可以获得整个文档,但您无法获得一部分。所以,你得到了文档,然后你通过一个小函数来寻找索引;)
-
嘿,这个小功能怎么样? :) 我可以在我的节点应用程序中实现它吗?我对这一切都很陌生。
-
看看 aydio 的答案 ;) 因此,您创建了一个库,用于使用此函数进行基本操作。你需要。 ;) 编辑:哦,是你哈哈
标签: arrays node.js mongodb object