MongoDB:如何定义架构? [英] MongoDB: How to define a schema?

查看:43
本文介绍了MongoDB:如何定义架构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个使用MongoDB作为数据库的应用程序.该应用程序利用了一些集合.

So I have an application that uses MongoDB as a database. The application makes use of a few collections.

我何时以及如何去定义数据库的模式",其中包括设置所有集合以及所需的索引?

When and how should I go about defining the "schema" of the database which includes setting up all the collections as well as indexes needed?

AFAIK,您无法在MongoDB中定义空集合(如果我做错了,请更正我,如果可以的话,基本上可以回答这个问题).我应该为每个集合插入一个虚拟值,并使用它来设置我的所有索引吗?

AFAIK, you are unable to define empty collections in MongoDB (correct me if I am wrong, if I can do this it will basically answer this question). Should I insert a dummy value for each collection and use that to setup all my indexes?

最佳做法是什么?

推荐答案

您不在MongoDB中创建集合.
无论它们是否存在",您都可以立即开始使用它们.

You don't create collections in MongoDB.
You just start using them immediately whether they "exist" or not.

现在定义模式".就像我说的那样,您只是开始使用集合,因此,如果需要确保索引,请继续执行此操作.没有创建收藏.首次修改(创建索引计数)时,任何集合都将有效创建.

Now to defining the "schema". As I said, you just start using a collection, so, if you need to ensure an index, just go ahead and do this. No collection creation. Any collection will effectively be created when you first modify it (creating an index counts).

> db.no_such_collection.getIndices()
[ ]
> db.no_such_collection.ensureIndex({whatever: 1})
> db.no_such_collection.getIndices()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "whatever" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "whatever_1"
        }
]

这篇关于MongoDB:如何定义架构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆