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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?