MongoDBで1つのコレクションのフィールドが他のコレクションよりも大きい2つのコレクションを集約するにはどうすればよいですか?
これには、$lookupを使用できます。ドキュメントを使用してコレクションを作成しましょう-
> db.demo446.insert([
... { "ProductName": "Product1", "ProductPrice": 60 },
... { "ProductName": "Product2", "ProductPrice": 90 }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}) find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo446.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60 }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90 } 以下は、ドキュメントを使用して2番目のコレクションを作成するためのクエリです-
> db.demo447.insert([
...
... { "ProductName": "Product1", "ProductPrice": 40 },
... { "ProductName": "Product2", "ProductPrice": 70 }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}) find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo447.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 }
{ "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } 以下は、一方のコレクションのフィールドがもう一方のコレクションよりも大きい2つのコレクションを集約するためのクエリです-
> var rate = 1;
> db.demo446.aggregate([
... { "$match": { "ProductPrice": { "$exists": true }, "ProductName": { "$exists": true } } },
... {
... "$lookup": {
... "from": "demo447",
... "localField": "ProductName",
... "foreignField": "ProductName",
... "as": "demo447"
... }
... },
... { "$unwind": "$demo447" },
... {
... "$redact": {
... "$cond": [
... {
... "$gt": [
... "$ProductPrice", {
... "$add": [
... { "$multiply": [ "$demo447.ProductPrice",rate ] },
... 3
... ]
... }
... ]
... },
... "$$KEEP",
... "$$PRUNE"
... ]
... }
... }
... ]) これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 } }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } } -
MongoDBコレクション内のすべてのドキュメントに新しいフィールドを追加する方法
新しいフィールドを追加するには、MongoDBで$addFieldsを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo712.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea85f675d33e20ed1097b82") } > db.demo712.insertOne({"
-
MongoDBコレクションから重複を削除するにはどうすればよいですか?
このために、「 unique:true」を設定します 」つまり、一意の制約を使用し、次の構文のように重複を挿入しないようにします- db.yourCollectionName.ensureIndex({yourFieldName: 1}, {unique: true, dropDups: true}) 上記の構文を理解するために、ドキュメントを使用してコレクションを作成しましょう。ここでは、重複挿入は許可されません- > db.demo604.ensureIndex({FirstName: 1}, {unique: true, dropDups: true});{ &nb