특정 필드가 포함된 문서를 찾으려면 $exists를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2a31627c0c63e7dba69") } >db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a") } > db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b") } >db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c") }
find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo247.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e46b2a31627c0c63e7dba69"), "ClientDetails" : [ { "ClientFirstName" : "Chris", "ClientAge" : 34 } ] } { "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [ { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 } ] } { "_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientAge" : 33 } ] } { "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 } ] }
다음은 특정 필드를 포함하는 문서를 찾는 쿼리입니다 -
> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [ { "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 } ] } { "_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [ { "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 } ] }