首页 > 解决方案 > 如何在mongodb中查询一个数组

问题描述

试图用另一个条件过滤一个数组来查询我的 MongoDB 数据库

我尝试使用elemMatch与查询完全匹配,但没有成功。

这是我的代码我的发货模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const ShipmentSchema = new Schema({
  warehouseNo:{
    type: String,
    ref: 'users.unitNo'
  },
  packages:[
    {
        category:{
            type: String
        },
        quantity:{
            type: String
        },
        description:{
            type: String
        },
        trackingno:{
            type: String,
        },
        date:{
            type: Date,
            default: Date.now
        },
        length:{
            type: Number
        },
        width:{
            type: Number
        },
        height:{
            type: Number
        },
        weight:{
            type: Number
        },
        fee:{
            type: Number, 
        },
        status: {
            type: String,
            default: "In warehouse"
        },
  },
],

  shippingMode:{
    type: String,
  },

 date:{
        type: Date,
        default: Date.now
 }
});

module.exports = Shipments = mongoose.model('shipments', ShipmentSchema);

这是我的节点 js。

// @route   GET api/user/package
// @desc    Get all package
// @access  Private
router.get('/package', 
  passport.authenticate('jwt', { session: false }),

 (req, res) => {
  const errors = {};

  Shipments.findOne({warehouseNo : req.user.unitNo})
    .then(shipments => {
      if (shipments.packages.length === 0) {
        errors.nopackages = 'There are no packages for you yet';
        return res.status(404).json(errors);
      }
      res.json(shipments.packages);
    })
});

上面的代码在我的 mongoddb 中带来了每条记录,但是如果我尝试了下面的代码,我会要求它按包状态进行填充。我收到代码崩溃错误

// @route   GET api/user/package
// @desc    Get all package
// @access  Private
router.get('/package', 
  passport.authenticate('jwt', { session: false }),

 (req, res) => {
  const errors = {};

  Shipments.find({warehouseNo : req.user.unitNo, "packages.status": "In warehouse"})
    .then(shipments => {
      if (shipments.packages.length === 0) {
        errors.nopackages = 'There are no packages for you yet';
        return res.status(404).json(errors);
      }
      res.json(shipments.packages);
    })
});

我希望得到这样的东西

{
    "status": "In warehouse",
    "date": "2019-09-11T10:19:02.834Z",
    "_id": "5d78ca160e47be29e13253b5",
    "category": "liquid",
    "quantity": "10 pieces",
    "description": "garri",
    "trackingno": "MHS085533395",
    "weight": 123,
    "length": 12,
    "height": 12,
    "width": 13
  }

相反,我得到了这个

[
  {
    "status": "Shipped",
    "date": "2019-09-11T10:17:46.485Z",
    "_id": "5d78c9ca0e47be29e13253b4",
    "category": "liquid",
    "quantity": "10 pieces",
    "description": "garri",
    "trackingno": "SDG561920753",
    "weight": 123,
    "height": 12,
    "width": 13
  },
  {
    "status": "In warehouse",
    "date": "2019-09-11T10:19:02.834Z",
    "_id": "5d78ca160e47be29e13253b5",
    "category": "liquid",
    "quantity": "10 pieces",
    "description": "garri",
    "trackingno": "MHS085533395",
    "weight": 123,
    "length": 12,
    "height": 12,
    "width": 13
  }
]

标签: javascriptnode.jsmongodbmongodb-query

解决方案


您应该$elemMatch在密钥内部使用packages,即db.getCollection('shipments').find( {warehouseNo: "123"}, { packages: { $elemMatch: { status: "In warehouse" }}}).

例如:我有一个集合如下:

{
"_id" : 1.0,
"name" : {
    "first" : "John",
    "last" : "Backus"
},
"birth" : ISODate("1924-12-03T05:00:00.000Z"),
"death" : ISODate("2007-03-17T04:00:00.000Z"),
"contribs" : [ 
    "Fortran", 
    "ALGOL", 
    "Backus-Naur Form", 
    "FP"
],
"awards" : [ 
    {
        "award" : "W.W. McDowell Award",
        "year" : 1967.0,
        "by" : "IEEE Computer Society"
    }, 
    {
        "award" : "National Medal of Science",
        "year" : 1975.0,
        "by" : "National Science Foundation"
    }, 
    {
        "award" : "Turing Award",
        "year" : 1977.0,
        "by" : "ACM"
    }, 
    {
        "award" : "Draper Prize",
        "year" : 1993.0,
        "by" : "National Academy of Engineering"
    }
]

}

使用这样的查询:

db.getCollection('bios').find( {_id: 1.0 }, { Awards: { $elemMatch: { year: 1967.0 }}})

给了我一个结果:

{ "_id" : 1.0, "awards" : [ { "award" : "WW McDowell Award", "year" : 1967.0, "by" : "IEEE Computer Society" } ] }

希望这会帮助你。


推荐阅读