似乎几乎没有关于如何为MongoDB设计数据库的文档。所以我想我会先在这里发布我的问题。
假设此集合(fruits_inventory
)为例:
{
"name" : "Orange",
"type" : "citric",
"available" : 3
}
{
"name" : "Apple",
"type" : "pome",
"available" : 0
"note" : "Not shipping this month"
}
{
"name" : "Pear",
"type" : "pome",
"available" : 2
}
(No indexes set)
db.fruits_inventory.findOne({name:"Orange"},{"note":1});
此查询是否会搜索仅包含值为name
的字段Orange
的文档,并在第一次匹配时返回,即使它没有设置note
字段?或者它会继续搜索包含note
字段的文档吗?
如果我在name
上设置了唯一索引,那么上一个问题的答案是否会改变?
现在只有这两个问题。答案将不胜感激。
答案 0 :(得分:7)
我写了以下脚本:
// sofruit.js
db = db.getSiblingDB('test');
db.fruits_inventory.drop();
db.fruits_inventory.save({
"name" : "Orange",
"type" : "citric",
"available" : 3
});
db.fruits_inventory.save({
"name" : "Apple",
"type" : "pome",
"available" : 0,
"note" : "Not shipping this month"
});
db.fruits_inventory.save({
"name" : "Pear",
"type" : "pome",
"available" : 2
});
var a1 = db.fruits_inventory.findOne({name:"Orange"},{"note":1});
db.fruits_inventory.ensureIndex({name:1}, {unique:true});
var a2 = db.fruits_inventory.findOne({name:"Orange"},{"note":1});
然后我从mongo shell运行它并得到:
> load('../mongojs/sofruit.js');
> a1
{ "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") }
> a2
{ "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") }
>
所以,答案是“是的”,它将返回第一个命中,即使它没有设置“注释”字段。添加索引不会改变它。
答案 1 :(得分:3)
您可以直接连接到mongodb并进行检查:
MongoDB shell version: 2.0.0
connecting to: test
> use test
switched to db test
> db.fruits_inventory.save({
... "name" : "Orange",
... "type" : "citric",
... "available" : 3
... });
> db.fruits_inventory.save({
... "name" : "Pear",
... "type" : "pome",
... "available" : 2
... })
> db.fruits_inventory.save({
... "name" : "Apple",
... "type" : "pome",
... "available" : 0,
... "note" : "Not shipping this month"
... })
> db.fruits_inventory.find()
{ "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0"), "name" : "Orange", "type" : "citric", "available" : 3 }
{ "_id" : ObjectId("4e7d101b626e0ab7b5074bb1"), "name" : "Pear", "type" : "pome", "available" : 2 }
{ "_id" : ObjectId("4e7d1059626e0ab7b5074bb2"), "name" : "Apple", "type" : "pome", "available" : 0, "note" : "Not shipping this month" }
> db.fruits_inventory.find({name: "Orange"},{"note":1})
{ "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0") }
> db.fruits_inventory.ensureIndex({name:1}, {unique:true})
> db.fruits_inventory.find({name: "Orange"},{"note":1})
{ "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0") }
因此,在回答您的问题时,当您查询注释字段时,它将只返回id并且具有唯一索引没有区别。