MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

カーソルを繰り返し、MongoDBでドキュメントを印刷しますか?


これには、printjsonを使用します。まず、ドキュメントを使用してコレクションを作成しましょう-

> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442")
}
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443")
}
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444")
}
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445")
}

以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-

> db.cursorDemo.find().pretty();

これにより、次の出力が生成されます-

{
   "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
   "StudentFullName" : "John Smith",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
   "StudentFullName" : "John Doe",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
   "StudentFullName" : "Carol Taylor",
   "StudentAge" : 20
}
{
   "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
   "StudentFullName" : "Chris Brown",
   "StudentAge" : 24
}

以下は、printjson-

を使用してドキュメントを反復および印刷するためのクエリです。
> db.cursorDemo.find().forEach(printjson);

これにより、次の出力が生成されます-

{
   "_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
   "StudentFullName" : "John Smith",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
   "StudentFullName" : "John Doe",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
   "StudentFullName" : "Carol Taylor",
   "StudentAge" : 20
}
{
   "_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
   "StudentFullName" : "Chris Brown",
   "StudentAge" : 24
}

「StudentFullName」や「StudentAge」などの特定のフィールドのみが必要な場合の2番目のクエリは次のとおりです-

> db.cursorDemo.find({}, { "StudentFullName": 1,"StudentAge":1, "_id": 0 }).forEach(printjson)

これにより、次の出力が生成されます-

{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }

  1. MongoDBとPython

    MongoDBは、広く使用されているドキュメントデータベースであり、NoSQLDBの形式でもあります。 Pythonは、いくつかのpythonモジュールを介してMongoDBと対話し、MongoDB内でデータを作成および操作できます。この記事では、その方法を学びます。ただし、PythonがMongoDBに接続して実行する前に、MongoDBがシステムですでに使用可能になっている必要があります。システムにMongoDBをセットアップするには、MongoDBチュートリアルにアクセスしてください。 ここに.. pymongoをインストールする MongoDBと対話するには、モジュール名pymong

  2. MongoDBの集約と投影?

    このために、aggregate()と一緒に$projectを使用します。集約された$projectは、要求されたフィールドを持つドキュメントをパイプラインの次のステージに渡します。 ドキュメントを使用してコレクションを作成しましょう- > db.demo762.insertOne({ ...    "_id" : { ...       "userId":101, ...       "userName":"Chris" ...