Add new Validator to Existing Collection

annadurai

I'm trying to add new field (LastLoginDate of type Date) to a existing collection. Here is my sample script:

db.createCollection( "MyTestCollection",
   { "validator": { "$or":
       [
          { "username": { "$type": "string" } },
          { "notes": { "$type": "string" } }
       ]
    }
   }
)

db.getCollectionInfos({name: "MyTestCollection"});
  [
     {
        "name" : "MyTestCollection",
        "options" : {
           "validator" : {
              "$or" : [
                 {
                    "username" : {
                       "$type" : "string"
                    }
                 },
                 {
                    "notes" : {
                       "$type" : "string"
                    }
                 }
              ]
           }
        }
     }
  ]

What is the best way to add new field LastLoginDate : { $type: "date" }, to this existing collection "MyTestCollection".

Adding new document or updating existing collection with new field may create this field. But i'm not sure how to enforce the date type on the new field. After adding new filed, if i execute the following command again, it doesn't show type validator for newly added field.

Neil Lunn

I "should" probably prefix this with one misconception in your question. The fact is MongoDB differs from traditional RDBMS in that it is "schemaless" and you do not in fact need to "create fields" at all. So this differs from a "table schema" where you cannot do anything until the schema changes. "Validation" however is a different thing as well as a "still" relatively new feature as of writing.

If you want to "add a validation rule" then there are methods which depend on the current state of the collection. In either case, there actually is no "add to" function, but the action instead is to "replace" all the validation rules with new ones to specify. Read on for the rules of how this works.

Existing Documents

Where the collection has existing documents, as noted in the documentation

Existing Documents

You can control how MongoDB handles existing documents using the validationLevel option.

By default, validationLevel is strict and MongoDB applies validation rules to all inserts and updates. Setting validationLevel to moderate applies validation rules to inserts and to updates to existing documents that fulfill the validation criteria. With the moderate level, updates to existing documents that do not fulfill the validation criteria are not checked for validity.

This and the following example section are basically saying that in addition to the options on .createCollection() you may also modify an existing collection with documents, but should be "wary" that the present documents may not meet the required rules. Therefore use "moderate" if you are unsure the rule will be met for all documents in the collection.

In order to apply, you use the .runCommand() method at present to issue the "command" which sets the validation rules. Which is "validationLevel" from the passage above.

Since you have existing rules, we can use the `.getCollectionInfos() to retrieve them and then add the new rule and apply:

let validatior = db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator;

validator.$or.push({ "LastLoginDate": { "$type": "date" } });

db.runCommand({
  "collMod": "MyTestCollection",
  "validator": validator,
  "validationLevel": "moderate"
});

Of course as noted before, that if you are confident the documents all meet the conditions then you can apply "strict" as the default instead.

Empty Collection

If in the case is that the collection is actually "empty" with no documents at all or you may "drop" the collection since the current data is not of consequence, then you can simply vary the above and use .createCollection() in combination with .drop():

let validatior = db.getCollectionInfos({name: "MyTestCollection"})[0].options.validator;

validator.$or.push({ "LastLoginDate": { "$type": "date" } });

db.getCollection("MyTestCollection").drop();

db.createCollection( "MyTestCollection", { "validator": validator });

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Swift JSON add new key to existing dictionary

分類Dev

Add new environment to an existing release-build

分類Dev

Dataframe add new rows from existing ones

分類Dev

How to add a new column to an existing entity with typeorm

分類Dev

Add new array values to existing array position

分類Dev

How to add a new whosonfirst place to an existing pelias database?

分類Dev

Does ES support to add a new item into the nested field of existing document?

分類Dev

Add new column to dataframe depending on interqection of existing columns with pyspark

分類Dev

How to add new grid rows without clearing existing data

分類Dev

How to add new column to existing table and set it value based on existing column using EF migrations

分類Dev

pandas dataframe - add new row if new index, if existing then supplement the index with column data

分類Dev

How can I implement the ability to add a new task to an existing list (project) or to a new one

分類Dev

How can I add a new object to an existing Entity, PUT the data and have EF add it to my database?

分類Dev

Is it possible to add a new field to an existing field of RECORD type in bigquery from UI?

分類Dev

Firebase - How do I add a new field for each row in an existing database?

分類Dev

How to add a new key value pair to existing key value pair from list of dicts?

分類Dev

Add a new sheet using Input Box, check existing sheet names and invalid sheet names

分類Dev

Making a new database if not existing

分類Dev

Add existing user to Unity

分類Dev

add groupby to existing dataframe

分類Dev

Angular 4 Form Builder Array Add Validator

分類Dev

Add custom errors to vee validator(ErrorBag)

分類Dev

Cascade insert of new and existing entities

分類Dev

Firebase set method not adding data to an existing Collection

分類Dev

How to add JLabel to existing JTextField

分類Dev

Add another object into existing JSON

分類Dev

JavaScript add prototype to existing object

分類Dev

Add typings to firebase collection query

分類Dev

Python: create a new column from existing columns

Related 関連記事

  1. 1

    Swift JSON add new key to existing dictionary

  2. 2

    Add new environment to an existing release-build

  3. 3

    Dataframe add new rows from existing ones

  4. 4

    How to add a new column to an existing entity with typeorm

  5. 5

    Add new array values to existing array position

  6. 6

    How to add a new whosonfirst place to an existing pelias database?

  7. 7

    Does ES support to add a new item into the nested field of existing document?

  8. 8

    Add new column to dataframe depending on interqection of existing columns with pyspark

  9. 9

    How to add new grid rows without clearing existing data

  10. 10

    How to add new column to existing table and set it value based on existing column using EF migrations

  11. 11

    pandas dataframe - add new row if new index, if existing then supplement the index with column data

  12. 12

    How can I implement the ability to add a new task to an existing list (project) or to a new one

  13. 13

    How can I add a new object to an existing Entity, PUT the data and have EF add it to my database?

  14. 14

    Is it possible to add a new field to an existing field of RECORD type in bigquery from UI?

  15. 15

    Firebase - How do I add a new field for each row in an existing database?

  16. 16

    How to add a new key value pair to existing key value pair from list of dicts?

  17. 17

    Add a new sheet using Input Box, check existing sheet names and invalid sheet names

  18. 18

    Making a new database if not existing

  19. 19

    Add existing user to Unity

  20. 20

    add groupby to existing dataframe

  21. 21

    Angular 4 Form Builder Array Add Validator

  22. 22

    Add custom errors to vee validator(ErrorBag)

  23. 23

    Cascade insert of new and existing entities

  24. 24

    Firebase set method not adding data to an existing Collection

  25. 25

    How to add JLabel to existing JTextField

  26. 26

    Add another object into existing JSON

  27. 27

    JavaScript add prototype to existing object

  28. 28

    Add typings to firebase collection query

  29. 29

    Python: create a new column from existing columns

ホットタグ

アーカイブ