Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB를 사용하여 다른 순서의 값으로 정확한 Array Match를 찾는 방법은 무엇입니까?

<시간/>

다른 순서의 값과 정확히 일치하는 배열을 찾으려면 $all 연산자를 사용할 수 있습니다. 문서로 컬렉션을 만들어 봅시다. 다음은 쿼리입니다.

>db.exactMatchArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentGameScores":[45,78,98]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c94702d6669774125246c")
}
>db.exactMatchArrayDemo.insertOne({"StudentName":"Chris","StudentAge":23,"StudentGameScores":[45,78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c94a42d6669774125246d")
}

다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다.

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

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : ObjectId("5c9c94702d6669774125246c"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentGameScores" : [
      45,
      78,
      98
   ]
}
{
   "_id" : ObjectId("5c9c94a42d6669774125246d"),
   "StudentName" : "Chris",
   "StudentAge" : 23,
   "StudentGameScores" : [
      45,
      78
   ]
}

다음은 정확한 배열 일치를 찾는 쿼리입니다.

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 2, "$all": [ 78, 45 ] } }).pretty();

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : ObjectId("5c9c94a42d6669774125246d"),
   "StudentName" : "Chris",
   "StudentAge" : 23,
   "StudentGameScores" : [
      45,
      78
   ]
}

다음은 정확한 배열 일치를 찾는 쿼리이지만 순서는 중요하지 않습니다. 3개의 값이 있는 "StudentGameScores" 필드를 가져오기 위해 다른 크기를 설정했습니다.

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 3, "$all": [ 78, 45 ] } }).pretty();

그러면 다음과 같은 출력이 생성됩니다.

{
   "_id" : ObjectId("5c9c94702d6669774125246c"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentGameScores" : [
      45,
      78,
      98
   ]
}