首页 > 解决方案 > 我们如何过滤子文档 mongodb?

问题描述

给定一个类似的模式

const Schema = new mongoose.Schema({
  price: {type:Number},
 condition: {
    new: { type: Boolean, default: false },
    heat: { type: Boolean, default: false },
    AC: { type: Boolean, default: false }
  }
);

我只想找到那些新的为真,其余的可以是真或假。所以我们不关心子文档的其余部分。query = {new: true} 所以其余的键将是未定义的。我可以用非子文档来实现我想要的,这意味着那些不在子文档中的东西。

Model.find(查询)

我试过什么?:

1. query = {condition.new: true} I think it is improper syntax
2. query = {condition: {new: true}} this will return an empty list because every elements need to contain the rest of the element
3. query = {condition: {new: true, heat: {$or: [true, false], AC:{$or :[true, false]}}
This will return an empty list

标签: mongodbmongoosemongoose-schema

解决方案


您的第一个查询是正确的,但您需要将路径括在引号中。所以它应该是这样的:

db.collection.find({
  "condition.new": true
})

游乐场:https ://mongoplayground.net/p/GL09AqeR2Y4


推荐阅读