简体   繁体   中英

Comparing two subdocument fields in MongoDB

Given a document as such

{
  _id: '123456',
  items: [{
    itemId: 'abcd',
    qty: 1
    qtyMax: 2
  }, {
    itemId: 'defg',
    qty: 3,
    qtyMax: 3
  }]
}

I would like to match this document because items.qty < items.qtyMax in one of the subdocuments.

I am aware of $where , but it does not apply, here, because it would require writing the entire validation manually, checking items and looping through all the elements... I am hoping for a better solution.

You have a better way to do this now thanks to the aggregate pipeline that allows you to use computed values:

db.yourDBNameHere.aggregate( [ 
    { $project: 
        { isStock: 
            { $lt:["$items.qty", "$items.qtyMax"] } } }, 
    { $match: 
        { isStock: true, }}, 
])

This will use the "project" phase to create a computed value where it checks whether or not items quantity is less than items max, then in the "match" phase, only matches documents where that is true. isStock is just a variable name and can be substituted with whatever suits you.

https://docs.mongodb.com/manual/core/aggregation-pipeline/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM