2단계 깊이의 MongoDB 레코드를 찾으려면 MongoDB $where 내부를 반복합니다. 문서로 컬렉션을 만들자 −
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Chris",
... "StudentAge" : 23
... },
... "SecondPosition" : {
... "StudentName" : "David",
... "StudentAge" : 20
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804e2fb0f3fa88e2279069")
}
> db.demo468.insertOne(
... {
... "_id" : new ObjectId(),
... "FirstPosition" : {
... "StudentName" : "Carol",
... "StudentAge" : 21
... },
... "SecondPosition" : {
... "StudentName" : "John",
... "StudentAge" : 22
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e804fb0b0f3fa88e227906a")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo468.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e804e2fb0f3fa88e2279069"), "FirstPosition" : { "StudentName" : "Chris",
"StudentAge" : 23 }, "SecondPosition" : { "StudentName" : "David", "StudentAge" : 20 } }
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } } 다음은 2단계 깊이의 MongoDB 레코드를 찾는 쿼리입니다. -
> db.demo468.find({
... $where: function() {
... for (var i in this) {
... if (this[i]["StudentName"] == "John") {
... return true;
... }
... }
... return false;
... }
... }) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e804fb0b0f3fa88e227906a"), "FirstPosition" : { "StudentName" : "Carol",
"StudentAge" : 21 }, "SecondPosition" : { "StudentName" : "John", "StudentAge" : 22 } }