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

MongoDB에서 배열 일치를 구현하시겠습니까?

<시간/>

배열 일치에 $all을 사용합니다. $all 연산자는 필드 값이 지정된 모든 요소를 ​​포함하는 배열인 문서를 선택합니다. 문서로 컬렉션을 만들자 −

> db.demo668.createIndex({"ListOfSubject":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo668.insert({"ListOfSubject":["MySQL","Java","C"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["MongoDB","Python","C++"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["C#","Spring","Hibernate","MongoDB"]});
WriteResult({ "nInserted" : 1 })

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

> db.demo668.find();

이것은 다음과 같은 출력을 생성합니다 -

{ "_id" : ObjectId("5ea311df04263e90dac943d6"), "ListOfSubject" : [ "MySQL", "Java", "C" ] }
{ "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] }
{ "_id" : ObjectId("5ea311e104263e90dac943d8"), "ListOfSubject" : [ "C#", "Spring", "Hibernate", "MongoDB" ] }

다음은 배열 일치에 대한 쿼리입니다 -

> db.demo668.find({"ListOfSubject":{ $all:["MongoDB","C++"]}});

이것은 다음과 같은 출력을 생성합니다 -

{ "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] }