MongoDB按字段值查询子文档

时间:2018-06-21 16:23:26

标签: node.js mongodb mongoose

因此我为供应商提供了以下架构:

 /**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Address = require('./Address.js'),
    AddressSchema = mongoose.model('Address').schema,
    Product = require('./Product.js'),
    ProductSchema = mongoose.model('Product').schema;

// Create a new schema for the reviews collection with all the relevant information for a review
var Schema = mongoose.Schema;

var Supplier = new Schema(
    {
        name: String,
        address: AddressSchema,
        location: {
            type: {type:String, default: 'Point'},
            coordinates: [Number] // [<longitude>, <latitude>]
        },
        products: [ProductSchema]
    }
);

Supplier.index({location: '2dsphere'});

var SupplierModel = mongoose.model('Supplier', Supplier );
// export the review model
module.exports = SupplierModel;

我系统中的产品有一个“已验证”字段,它是一个布尔值。在我的其中一条路线中,我想查询数据库以查找所有未验证产品的供应商,以便随后在页面中呈现这些产品。

我尝试了此方法,但是无论“ verified”是true还是false,它都会返回所有子文档:

exports.admin_accept_product_get = function (req, res) {
    Supplier.find({'products.verified' : false}, function(err, docs) {
        res.render('admin_accept_product', { user : req.user, suppliers: docs });
    });
};

感谢您的帮助

编辑:

上一个查询将返回以下数据:

{
    "_id" : ObjectId("5b2b839a2cf8820e304d7413"),
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            -16.5122377, 
            28.4028329
        ]
    },
    "name" : "Tienda1",
    "products" : [ 
        {
            "verified" : true,
            "_id" : ObjectId("5b2b83d32cf8820e304d7420"),
            "title" : "Vodka",
            "inStock" : 15,
            "typeOfItem" : "alcohol",
            "sellingPrice" : 15,
            "image" : "public/upload/15295784515201529168557789bottle.png",
            "typeOfAlcohol" : "vodka"
        }, 
        {
            "verified" : false,
            "_id" : ObjectId("5b2b848f8c59960c44df09cd"),
            "title" : "Whisky",
            "inStock" : 40,
            "typeOfItem" : "alcohol",
            "sellingPrice" : 15,
            "image" : "public/upload/15295786395491529323314298whisky.png",
            "typeOfAlcohol" : "whisky"
        }
    ],
    "__v" : 2
}

我希望查询不返回首个产品,因为“已验证== true”

1 个答案:

答案 0 :(得分:1)

您需要使用$elemMatch查找文档,并使用$elemMatch进行数据投影

db.collection.find({
  products: {
    $elemMatch: {
      verified: false
    }
  }
},
{
  products: {
    $elemMatch: {
      verified: false
    }
  },
  location: 1
})

输出

[
  {
    "_id": ObjectId("5b2b839a2cf8820e304d7413"),
    "products": [
      {
        "_id": ObjectId("5b2b848f8c59960c44df09cd"),
        "image": "public/upload/15295786395491529323314298whisky.png",
        "inStock": 40,
        "sellingPrice": 15,
        "title": "Whisky",
        "typeOfAlcohol": "whisky",
        "typeOfItem": "alcohol",
        "verified": false
      }
    ]
  }
]

检查here