mongodb操作使用笔记
发布日期:2021-09-20 08:07:31 浏览次数:38 分类:技术文章

本文共 546 字,大约阅读时间需要 1 分钟。

1.使用$filter过滤数组中的元素。

比如一个文档是 

{   _id: 1,   items: [     { item_id: 23, quantity: 3, price: 110 },     { item_id: 103, quantity: 4, price: 5 },     { item_id: 38, quantity: 1, price: 300 }   ]}

只显示items中的price大于100的元素:

db.sales.aggregate([   {      $project: {         items: {            $filter: {               input: "$items",               as: "item",               cond: { $gte: [ "$$item.price", 100 ] }            }         }      }   }])

或者这样:

db.test.find({}, {items:{$elemMatch:{"price":{$gt:100}}}})

但是这个方法只会返回一个符合条件的元素(尽管可能会有多个符合条件的。)

转载地址:https://blog.csdn.net/caiyiii/article/details/114933227 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:curl提示错误“ Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter”的解决办法
下一篇:mysql优化摘要

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月14日 04时44分15秒