mapReduce()関数を使用して代替ドキュメントを表示し、フィールド値を均等に出力するMongoDBクエリ
ドキュメントを使用してコレクションを作成しましょう-
> db.demo636.insert({id:1});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:2});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:3});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:4});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:5});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:6});
WriteResult({ "nInserted" : 1 })> find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo636.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e9c127b6c954c74be91e6d2"), "id" : 1 }
{ "_id" : ObjectId("5e9c127e6c954c74be91e6d3"), "id" : 2 }
{ "_id" : ObjectId("5e9c127f6c954c74be91e6d4"), "id" : 3 }
{ "_id" : ObjectId("5e9c12816c954c74be91e6d5"), "id" : 4 }
{ "_id" : ObjectId("5e9c12836c954c74be91e6d6"), "id" : 5 }
{ "_id" : ObjectId("5e9c12896c954c74be91e6d7"), "id" : 6 } 以下は、mapReduce()を実装し、偶数の値のみを表示するためのクエリです-
> db.demo636.mapReduce(
... function () {
... oddCounter++;
... var id= this._id;
... delete this._id;
... if ( oddCounter % d != 0 )
... emit(id, this );
... },
... function() {},
... {
... "scope": { "oddCounter": 0, "d": 2 },
... "out": { "inline": 1 }
... }
... ) これにより、次の出力が生成されます-
{
"results" : [
{
"_id" : ObjectId("5e9c127b6c954c74be91e6d2"),
"value" : {
"id" : 1
}
},
{
"_id" : ObjectId("5e9c127f6c954c74be91e6d4"),
"value" : {
"id" : 3
}
},
{
"_id" : ObjectId("5e9c12836c954c74be91e6d6"),
"value" : {
"id" : 5
}
}
],
"timeMillis" : 29,
"counts" : {
"input" : 6,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1
} -
MongoDB 4でドキュメントを並べ替えて、単一のフィールドのみを表示するにはどうすればよいですか?
MongoDB 4でドキュメントを並べ替えるには、sort()を使用します。並べ替えられた単一のフィールドのみを表示するには、1に設定します。 ドキュメントを使用してコレクションを作成しましょう- > db.demo611.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e987110f6b89257f5584d83") } > db.demo61
-
コレクション内のドキュメントの各フィールドを数式で更新するMongoDBクエリ?
コレクション内のドキュメントの各フィールドを数式で更新するには、MongoDB update()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo749.insertOne({"details":[{"id":1,a:10},{"id":2,a:5},{"id":3,a:20}]}); { "acknowledged" : true, "insertedId" : ObjectId(