MongoDB获取1字段的所有值 [英] MongoDB get all values of 1 field
本文介绍了MongoDB获取1字段的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我知道在mongodb中,我可以获取所有值,然后遍历它们,但是我想知道在mongodb中是否可以选择仅获取某个字段.
So I know that in mongodb, I can get all values and then iterate through them but I was wondering if in mongodb there is an option to get only a certain field.
例如,假设我的收藏的结构如下:
So for example suppose my collection is structured as follows:
{_id:
{
field1,field2,field3}
}
{description:
{
field1,field2,field3,
data:{
field1,field2,field3
}
}
}
{otherdata:
{field1,field2,field3}
}
现在,我需要description.data.field1的值,那么有关如何执行此操作的任何建议?
Now, I need the value of description.data.field1 so any suggestions on how to do that?
到目前为止,我已经尝试使用以下命令:
So far I have tried using following commands:
db.module.collection.description.data.find()
db.module.collection.description.find({'data':1})
db.module.collection.find('description.data.data':1})
但是显然,它们没有用.
But obviously, they did not work.
有什么建议吗?
推荐答案
首先,JSON的结构不正确.正确的结构应为:
First of all, the structure of your JSON isn't correct. The correct structure should be:
{
_id:{
field1: "",
field2: "",
field3: ""
},
description:{
field1: "",
field2: "",
field3: "",
data:{
field1: "",
field2: "",
field3: ""
}
},
otherdata:{
field1: "",
field2: "",
field3: ""
}
}
现在,您可以使用 Projections
类似这样的东西:
db.collection.find({}, {description.data.field1: 1})
这篇关于MongoDB获取1字段的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文