登录
首页 >  Golang >  Go问答

查询 MongoDB 中订单 id 1 存在但订单 id 2 不存在的文档

来源:stackoverflow

时间:2024-02-21 14:54:23 151浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《查询 MongoDB 中订单 id 1 存在但订单 id 2 不存在的文档》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我有这套文件

{_id: objectid(""),orderid:1,productname:"iphone 13"}
{_id: objectid(""),orderid:1,productname:"xiaomi 11"}
{_id: objectid(""),orderid:1,productname:"pocophone f1"}
{_id: objectid(""),orderid:1,productname:"samsung s22"}
{_id: objectid(""),orderid:2,productname:"iphone 13"}
{_id: objectid(""),orderid:2,productname:"xiaomi 11"}

我试图获取顺序为 1 但不是顺序 2 的产品名称,我的 mongodb 查询是:

{orderid:{$eq:orderid-1,$ne:orderid}}

但它不起作用,然后我尝试使用如下聚合操作:

{
    $match: {orderid:{$gte:orderid-1}} //this is because allways a will try to get the products name in max orderid - 1 to get that resutl with the last 2 orders
    $group:{
       _id: {productname: '$productName'}
       orders:{$push:'$orderid'}
       total:{$sum:1}
    }
    //Then here i'm trying to get just de maxorderid-1 docs that just have total equal 1 but i cant achive the result.
}

非常感谢您的支持和解答。


正确答案


如果我理解正确,你可以尝试这样的事情:

  • 首先将 $groupproductname 并将 orderids 存储在数组中
  • $与数组中的值匹配:$and 条件,其中存在 1 而不是 2
  • 然后使用 $unwind$project 重建对象,轴字段 root 保存在 $group 阶段
db.collection.aggregate([
  {
    "$group": {
      "_id": "$productName",
      "orderids": {
        "$push": "$orderid"
      },
      "root": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$match": {
      "$and": [
        {
          "orderids": 1
        },
        {
          "orderids": {
            "$ne": 2
          }
        }
      ]
    }
  },
  {
    "$unwind": "$root"
  },
  {
    "$project": {
      "_id": "$root._id",
      "orderid": "$root.orderid",
      "productName": "$root.productName"
    }
  }
])

示例here

此外,如果您只需要 productname,则该值存储在该组的 id 中,所以不需要最后两个阶段。点赞this example

本篇关于《查询 MongoDB 中订单 id 1 存在但订单 id 2 不存在的文档》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>