programing

Mongo: 특정 필드가 없는 항목 찾기

jooyons 2023. 3. 26. 11:14
반응형

Mongo: 특정 필드가 없는 항목 찾기

MongoDB에서 특정 필드가 없는 문서를 검색하려면 어떻게 해야 합니까?

, $exists를 사용하면 가능합니다.

db.things.find( { a : { $exists : false } } ); // return if a is missing

true일 경우 $exists는 필드가 포함된 문서(필드 값이 null인 문서 포함)와 일치합니다.가 false일 경우 쿼리는 필드를 포함하지 않는 문서만 반환합니다.

필드가 누락되어도 상관없습니다.null(혹은 그렇지 않은 경우)null그러면 보다 짧고 안전한 를 사용할 수 있습니다.

db.things.find( { a : null } ); // return if a is missing or null

그래서 더 안전하다.$exists돌아온다true필드가 늘인 경우에도 대부분의 경우 원하는 결과가 아니므로 NPE가 발생할 수 있습니다.

mongoose(v6)를 사용하고 있는 분들을 위해 여기에 있는 참고용입니다.$existsmongoose 스키마에서 정의되지 않은 필드를 찾기 위해 mongoose v6는 필드를 이스케이프합니다.

https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict 를 참조해 주세요.

예를 들어 다음과 같습니다.

const userSchema = new Schema({ name: String });
const User = mongoose.model('User', userSchema);

// By default, this is equivalent to `User.find()` because Mongoose filters out `notInSchema`
await User.find({ notInSchema: 1 });

// Set `strictQuery: false` to opt in to filtering by properties that aren't in the schema
await User.find({ notInSchema: 1 }, null, { strictQuery: false });
// equivalent:
await User.find({ notInSchema: 1 }).setOptions({ strictQuery: false });

언급URL : https://stackoverflow.com/questions/5719408/mongo-find-items-that-dont-have-a-certain-field

반응형