Mongodb-query-document

提供:Dev Guides
移動先:案内検索

MongoDB-クエリドキュメント

この章では、MongoDBコレクションからドキュメントをクエリする方法を学びます。

find()メソッド

MongoDBコレクションからデータをクエリするには、MongoDBの* find()*メソッドを使用する必要があります。

構文

  • find()*メソッドの基本的な構文は次のとおりです-
>db.COLLECTION_NAME.find()
  • find()*メソッドは、構造化されていない方法ですべてのドキュメントを表示します。

mycolという名前のコレクションを作成したと仮定します-

> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>

そして、以下に示すようにinsert()メソッドを使用してそれに3つのドキュメントを挿入しました-

> db.mycol.insert([
    {
        title: "MongoDB Overview",
        description: "MongoDB is no SQL database",
        by: "tutorials point",
        url: "http://www.finddevguides.com",
        tags: ["mongodb", "database", "NoSQL"],
        likes: 100
    },
    {
        title: "NoSQL Database",
        description: "NoSQL database doesn't have tables",
        by: "tutorials point",
        url: "http://www.finddevguides.com",
        tags: ["mongodb", "database", "NoSQL"],
        likes: 20,
        comments: [
            {
                user:"user1",
                message: "My first comment",
                dateCreated: new Date(2013,11,10,2,35),
                like: 0
            }
        ]
    }
])

次のメソッドは、コレクション内のすべてのドキュメントを取得します-

> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.finddevguides.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.finddevguides.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>

pretty()メソッド

フォーマットされた方法で結果を表示するには、pretty()メソッドを使用できます。

構文

>db.COLLECTION_NAME.find().pretty()

次の例では、mycolという名前のコレクションからすべてのドキュメントを取得し、読みやすい形式に配置しています。

> db.mycol.find().pretty()
{
    "_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
    "title" : "MongoDB Overview",
    "description" : "MongoDB is no SQL database",
    "by" : "tutorials point",
    "url" : "http://www.finddevguides.com",
    "tags" : [
        "mongodb",
        "database",
        "NoSQL"
    ],
    "likes" : 100
}
{
    "_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
    "title" : "NoSQL Database",
    "description" : "NoSQL database doesn't have tables",
    "by" : "tutorials point",
    "url" : "http://www.finddevguides.com",
    "tags" : [
        "mongodb",
        "database",
        "NoSQL"
    ],
    "likes" : 20,
    "comments" : [
        {
            "user" : "user1",
            "message" : "My first comment",
            "dateCreated" : ISODate("2013-12-09T21:05:00Z"),
            "like" : 0
        }
    ]
}

findOne()メソッド

find()メソッドとは別に、1つのドキュメントのみを返す* findOne()*メソッドがあります。

構文

>db.COLLECTIONNAME.findOne()

次の例では、MongoDB Overviewというタイトルのドキュメントを取得します。

> db.mycol.findOne({title: "MongoDB Overview"})
{
    "_id" : ObjectId("5dd6542170fb13eec3963bf0"),
    "title" : "MongoDB Overview",
    "description" : "MongoDB is no SQL database",
    "by" : "tutorials point",
    "url" : "http://www.finddevguides.com",
    "tags" : [
        "mongodb",
        "database",
        "NoSQL"
    ],
    "likes" : 100
}

MongoDBでのRDBMS Where句の同等物

何らかの条件に基づいてドキュメントを照会するには、次の操作を使用できます。

Operation Syntax Example RDBMS Equivalent
Equality \{<key>:\{$eg;<value>}} db.mycol.find(\{"by":"tutorials point"}).pretty() where by = 'tutorials point'
Less Than \{<key>:\{$lt:<value>}} db.mycol.find(\{"likes":\{$lt:50}}).pretty() where likes < 50
Less Than Equals \{<key>:\{$lte:<value>}} db.mycol.find(\{"likes":\{$lte:50}}).pretty() where likes ⇐ 50
Greater Than \{<key>:\{$gt:<value>}} db.mycol.find(\{"likes":\{$gt:50}}).pretty() where likes > 50
Greater Than Equals \{<key>:\{$gte:<value>}} db.mycol.find(\{"likes":\{$gte:50}}).pretty() where likes >= 50
Not Equals \{<key>:\{$ne:<value>}} db.mycol.find(\{"likes":\{$ne:50}}).pretty() where likes != 50
Values in an array \{<key>:\{$in:[<value1>, <value2>,……<valueN>]}} db.mycol.find(\{"name":\{$in:["Raj", "Ram", "Raghu"]}}).pretty() Where name matches any of the value in :["Raj", "Ram", "Raghu"]
Values not in an array \{<key>:\{$nin:<value>}} db.mycol.find(\{"name":\{$nin:["Ramu", "Raghav"]}}).pretty() Where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all

およびMongoDB内

構文

AND条件に基づいてドキュメントをクエリするには、$ andキーワードを使用する必要があります。 以下は、ANDの基本的な構文です-

>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })

次の例は、「チュートリアルポイント」で作成され、タイトルが「MongoDB Overview」であるすべてのチュートリアルを示します。

> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
    "_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
    "title" : "MongoDB Overview",
    "description" : "MongoDB is no SQL database",
    "by" : "tutorials point",
    "url" : "http://www.finddevguides.com",
    "tags" : [
        "mongodb",
        "database",
        "NoSQL"
    ],
    "likes" : 100
}
>

上記の例では、同等のwhere句は 'where by =' tutorials point 'AND title =' MongoDB Overview になります。 find句では、キーと値のペアをいくつでも渡すことができます。

またはMongoDBで

構文

OR条件に基づいてドキュメントをクエリするには、 $ or キーワードを使用する必要があります。 以下は OR の基本的な構文です-

>db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

次の例は、「チュートリアルポイント」またはタイトルが「MongoDB Overview」で書かれたすべてのチュートリアルを示します。

>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview",
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.finddevguides.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

ANDとORを一緒に使用する

次の例は、10以上のいいね!を持ち、タイトルが「MongoDB Overview」またはbyが「tutorials point」であるドキュメントを示します。 同等のSQL where句は 'where likes> 10 AND(by =' tutorials point 'OR title =' MongoDB Overview ')'

>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
   {"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview",
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.finddevguides.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

MongoDBのNOR

構文

NOT条件に基づいてドキュメントをクエリするには、$ notキーワードを使用する必要があります。 以下は NOT の基本構文です-

>db.COLLECTION_NAME.find(
    {
        $not: [
            {key1: value1}, {key2:value2}
        ]
    }
)

以下に示すように、コレクション empDetails に3つのドキュメントを挿入したと仮定します-

db.empDetails.insertMany(
    [
        {
            First_Name: "Radhika",
            Last_Name: "Sharma",
            Age: "26",
            e_mail: "[email protected]",
            phone: "9000012345"
        },
        {
            First_Name: "Rachel",
            Last_Name: "Christopher",
            Age: "27",
            e_mail: "[email protected]",
            phone: "9000054321"
        },
        {
            First_Name: "Fathima",
            Last_Name: "Sheik",
            Age: "24",
            e_mail: "[email protected]",
            phone: "9000054321"
        }
    ]
)

次の例では、名が「Radhika」ではなく、姓が「Christopher」ではないドキュメントを取得します。

> db.empDetails.find(
    {
        $nor:[
            40
            {"First_Name": "Radhika"},
            {"Last_Name": "Christopher"}
        ]
    }
).pretty()
{
    "_id" : ObjectId("5dd631f270fb13eec3963bef"),
    "First_Name" : "Fathima",
    "Last_Name" : "Sheik",
    "Age" : "24",
    "e_mail" : "[email protected]",
    "phone" : "9000054321"
}

MongoDBにはない

構文

NOT条件に基づいてドキュメントをクエリするには、$ NOTキーワードを使用する必要があります。以下は NOT の基本構文です-

>db.COLLECTION_NAME.find(
    {
        $NOT: [
            {key1: value1}, {key2:value2}
        ]
    }
).pretty()

次の例では、年齢が25以下のドキュメントを取得します

> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
    "_id" : ObjectId("5dd6636870fb13eec3963bf7"),
    "First_Name" : "Fathima",
    "Last_Name" : "Sheik",
    "Age" : "24",
    "e_mail" : "[email protected]",
    "phone" : "9000054321"
}