MongoDB有多聪明?

thw*_*hwd -4 database-design mongodb

似乎几乎没有关于如何为MongoDB设计数据库的文档.所以我想我会先在这里发布我的问题.

假设此collection(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
}
Run Code Online (Sandbox Code Playgroud)

(No indexes set)

1)现场选择

db.fruits_inventory.findOne({name:"Orange"},{"note":1});

此查询是否会查找仅包含name具有值的字段的文档,Orange并返回第一个匹配,即使它没有note字段集?或者它会不断搜索包含note字段的文档?

2)具有独特的索引

如果我设置了一个唯一索引name,那么上一个问题的答案是否会改变?

现在只有这两个问题.答案将不胜感激.

Chr*_*tin 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});
Run Code Online (Sandbox Code Playgroud)

然后我从mongo shell运行它并得到:

> load('../mongojs/sofruit.js');
> a1
{ "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") }
> a2
{ "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") }  
>
Run Code Online (Sandbox Code Playgroud)

所以,答案是"是",它将返回第一个命中,即使它没有设置"注释"字段.添加索引不会改变这一点.