问题
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}
}
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.
Any suggestions?
回答1:
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: ""
}
}
Now for what you need, you can use Projections
Something like this:
db.collection.find({}, {description.data.field1: 1})
来源:https://stackoverflow.com/questions/36460377/mongodb-get-all-values-of-1-field