MongoDBで簡単な検証を実行しますか?
MongoDBでの検証には、バリデーターを使用します。以下は、MongoDBのコレクションで検証を作成するためのクエリです-
> db.createCollection( "demo437" , {
... validator: { $jsonSchema: {
... bsonType: "object",
... required: [ "FirstName", "LastName"],
... properties: {
... FirstName: {
... bsonType: "string",
... description: "This is required" },
... LastName: {
... bsonType: "string",
... description: "This is required" }
...
... }
... }}})
{ "ok" : 1 } ドキュメントを使用してコレクションを作成しましょう-
> db.demo437.insertOne({"FirstName":"John","LastName":1234});
2020-03-22T17:49:55.590+0530 E QUERY [js] WriteError: Document failed validation :
WriteError({
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5e7757ebbbc41e36cc3cae9a"),
"FirstName" : "John",
"LastName" : 1234
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
>
> db.demo437.insertOne({"FirstName":"John","LastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7757f7bbc41e36cc3cae9b")
}
> db.demo437.insertOne({"FirstName":9887,"LastName":"Miller"});
2020-03-22T17:50:29.631+0530 E QUERY [js] WriteError: Document failed validation :
WriteError({
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5e77580dbbc41e36cc3cae9c"),
"FirstName" : 9887,
"LastName" : "Miller"
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
>
>
> db.demo437.insertOne({"FirstName":"David","LastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e775816bbc41e36cc3cae9d")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo437.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e7757f7bbc41e36cc3cae9b"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5e775816bbc41e36cc3cae9d"), "FirstName" : "David", "LastName" : "Miller" } -
MongoDB全文検索を実行します
MongoDBでの全文検索には、$textを使用します。 $ textは、フィールドのコンテンツに対してテキスト検索を実行します。ドキュメントを使用してコレクションを作成しましょう- > db.demo654.createIndex({Name:"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter"
-
MongoDBで一括挿入を実行しますか?
MongoDBでの一括挿入には、initializeUnorderedBulkOp()を使用します。ドキュメントを使用してコレクションを作成しましょう- > var bulkInsertDoc = db.demo663.initializeUnorderedBulkOp(); > bulkInsertDoc.insert( { Name: "John",CountryName:"US"} ); > bulkInsertDoc.insert( { Name: "Chris",CountryName:"UK&q