douwen9343 2015-04-27 16:28
浏览 46
已采纳

如何通过嵌入文档中的字段来订购mongoDB查询?

I have these documents in a mongoDB:

    /* 1 */
{
    "_id" : ObjectId("553ce99a39108e2b7c1edeb9"),
    "coleccion" : "aplicaciones",
    "nombre" : "Mascotas",
    "descripcion" : "Censo de mascotas",
    "tipo" : "privada"
}

/* 2 */
{
    "_id" : ObjectId("553e316e39108e802a1edeb9"),
    "coleccion" : "aplicaciones",
    "nombre" : "otra aplicacionn",
    "descripcion" : "w aplicacion",
    "tipo" : "privada",
    "campoId" : [ 
        {
            "id" : "1430145364",
            "id_campo" : "553bffca39108eb163cff7aa",
            "orden" : 90
        }, 
        {
            "id" : "1430145368",
            "id_campo" : "553bffed39108e346ccff7ab",
            "orden" : 100,
            "estado" : "0"
        }, 
        {
            "id" : "1430145370",
            "id_campo" : "553c001139108ebc63cff7aa",
            "orden" : 29,
            "estado" : "1"
        }, 
        {
            "id" : "1430145395",
            "id_campo" : "553c001139108ebc63cff7aa",
            "orden" : 9,
            "estado" : "0"
        }
    ]
}

I need to query and sort the data in ascending order of each document using the field " campoId.orden " and have executed this query:

db.getCollection('aplicaciones').find({}).sort({'campoId.orden' : -1})

but I do not get the order I want. can anyone suggest me a way?

  • 写回答

1条回答 默认 最新

  • douba9425 2015-04-27 17:01
    关注

    In your documents orden in nested array, so you should use mongo aggregation. So below step will follow :

    1> First check campoId exits or not $exists

    2> Then unwind campoId array $unwind

    3> Then group all fields $group

    So query as below :

    db.aplicaciones.aggregate({
        "$match": {
          "campoId": {
            "$exists": true // check here campoId presents or not using exists
          }
        }
      }, {
        "$unwind": "$campoId" // unwind campoId array 
      }, {
        "$sort": {
          "campoId.orden": -1
        }
      },
      //groups all fields
      {
        "$group": {
          "_id": "$_id",
          "coleccion": {
            "$first": "$coleccion"
          },
          "nombre": {
            "$first": "$nombre"
          },
          "descripcion": {
            "$first": "$descripcion"
          },
          "tipo": {
            "$first": "$tipo"
          },
          "campoId": {
            "$push": "$campoId"
          }
        }
      }).pretty()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办