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 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果