programing

Mongo 필드 A가 필드 B보다 큼

lovejava 2023. 6. 23. 21:09

Mongo 필드 A가 필드 B보다 큼

나는 Mongo에서 MySQL에서 이렇게 보이는 간단한 쿼리를 시도하고 있습니다.

select * from emails where bounceCount > sentCount;

지금까지.

db.email.find({ bounceCount : { $gt : sentCount } } );

하지만 이 오류가 발생합니다.

JS Error: ReferenceError: sentCount is not defined (shell):0

셸에서 sentCount를 참조하려면 어떻게 해야 합니까?

효과가 있을 것입니다.

db.emails.find({ $expr: { $gt: [ "$bounceCount" , "$sentCount" ] } });

다음은 제가 찾은 참조 자료입니다: https://docs.mongodb.com/manual/reference/operator/query/expr/ #op._S_expr

모두가 언급하는 것처럼 보입니다.$where그것이 무엇인지 실제로 알지 못한 채:

  • 느릿느릿
  • 불안정한(평가된)
  • MongoDB 내부가 아닌 JavaScript
  • 또한 2.4 이전 버전에서는 단일 스레드 및 글로벌 잠금 기능을 제공합니다.

약 99%의 사례에서 훨씬 더 나은 또 다른 방법은 집계 프레임워크를 사용하는 것입니다.

db.col.aggregate([
    {$project: {ab: {$cmp: ['$bounceCount','$sentCount']}}},
    {$match: {ab:{$gt:0}}}
])

db.so.find("this.bounceCount > this.sentCount")당신이 찾고 있는 것입니다.

동등:db.so.find({"$where":"this.bounceCount > this.sentCount"})

설명서: http://docs.mongodb.org/manual/reference/operator/where/

셸 출력:

> db.so.insert({bounceCount:1, sentCount:2})
> db.so.insert({bounceCount:5, sentCount:3})
> db.so.insert({bounceCount:5, sentCount:4})
> db.so.insert({bounceCount:5, sentCount:7})
> db.so.insert({bounceCount:9, sentCount:7})

> db.so.find()
{ "_id" : ObjectId("516d7f30675a2a8d659d7594"), "bounceCount" : 1, "sentCount" : 2 }
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f3d675a2a8d659d7597"), "bounceCount" : 5, "sentCount" : 7 }
{ "_id" : ObjectId("516d7f40675a2a8d659d7598"), "bounceCount" : 9, "sentCount" : 7 }

> db.so.find({"bounceCount":5})
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f3d675a2a8d659d7597"), "bounceCount" : 5, "sentCount" : 7 }

> db.so.find("this.bounceCount > this.sentCount")
{ "_id" : ObjectId("516d7f37675a2a8d659d7595"), "bounceCount" : 5, "sentCount" : 3 }
{ "_id" : ObjectId("516d7f3b675a2a8d659d7596"), "bounceCount" : 5, "sentCount" : 4 }
{ "_id" : ObjectId("516d7f40675a2a8d659d7598"), "bounceCount" : 9, "sentCount" : 7 }

$where 연산자를 사용하여 쿼리에서 Javascript 코드를 사용할 수 있습니다.

예를 들어 다음 작업을 수행합니다.

db.email.find({ $where: "this.bounceCount > this.sentCount" });

$where 연산자 http://docs.mongodb.org/manual/reference/operator/where/ #op._S_where에 대한 자세한 내용은 MongoDB 설명서 페이지를 참조하십시오.

언급URL : https://stackoverflow.com/questions/16042315/mongo-field-a-greater-than-field-b