두 필드 비교시 MongoDb 쿼리 조건
나는 모음이 T
두 필드를 : Grade1
그리고 Grade2
, 나는 조건을 가진 사람을 선택합니다 Grade1 > Grade2
내가 MySQL은 같은 쿼리를 얻을 수있는 방법?
Select * from T Where Grade1 > Grade2
$ where를 사용할 수 있습니다. 속도가 상당히 느리므로 (모든 레코드에서 Javascript 코드를 실행해야 함) 가능하면 색인화 된 쿼리와 결합하십시오.
db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
또는 더 콤팩트 :
db.T.find( { $where : "this.Grade1 > this.Grade2" } );
mongodb v.3.6 + 용 UPD
최근 답변에$expr
설명 된대로 사용할 수 있습니다.
쿼리가 $where
연산자 로만 구성된 경우 JavaScript 표현식 만 전달할 수 있습니다.
db.T.find("this.Grade1 > this.Grade2");
성능을 $redact
높이려면 파이프 라인 이있는 집계 작업을 실행 하여 주어진 조건을 충족하는 문서를 필터링하십시오.
$redact
파이프 라인의 기능을 통합 $project
하고 $match
그것을 사용 조건과 일치하는 모든 문서를 반환 필드 레벨 편집 구현하는 $$KEEP
파이프 라인 결과에서 사용하여 일치하지 않는 것들과 제거합니다 $$PRUNE
변수.
다음 집계 작업을 실행하면 $where
대규모 컬렉션에 사용하는 것보다 문서를 더 효율적으로 필터링 할 수 있습니다.을 사용하는 자바 스크립트 평가 대신 단일 파이프 라인과 네이티브 MongoDB 연산자 $where
를 사용하므로 쿼리 속도가 느려질 수 있습니다.
db.T.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$Grade1", "$Grade2" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
이는 두 개의 파이프 라인 통합을보다 간략화 버전 $project
과 $match
:
db.T.aggregate([
{
"$project": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
"Grade1": 1,
"Grade2": 1,
"OtherFields": 1,
...
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
와 MongoDB를 3.4 및 최신 :
db.T.aggregate([
{
"$addFields": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.
Compare query operators
vs aggregation comparison operators
.
Regular Query:
db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})
Aggregation Query:
db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})
In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:
import pymongo
from random import randrange
docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]
coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)
Using aggregate:
%timeit -n1 -r1 list(coll.aggregate([
{
'$project': {
'diff': {'$subtract': ['$Grade1', '$Grade2']},
'Grade1': 1,
'Grade2': 1
}
},
{
'$match': {'diff': {'$gt': 0}}
}
]))
1 loop, best of 1: 192 ms per loop
Using find and $where:
%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))
1 loop, best of 1: 4.54 s per loop
참고URL : https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields
'program tip' 카테고리의 다른 글
Visual Studio에서 새 클래스를 만들 때 새 클래스를 어떻게 기본값으로 공개합니까? (0) | 2020.08.30 |
---|---|
모듈에 대한 파이썬 명명 규칙 (0) | 2020.08.30 |
React.js의 setState 대 replaceState (0) | 2020.08.30 |
React 구성 요소가 다시 렌더링되는 이유 추적 (0) | 2020.08.30 |
Ruby에서 문자열 대신 기호를 사용하는 경우 (0) | 2020.08.30 |