MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Gruppenanzahl 2 Elementobjekt-Array mongodb

Sie haben nur 2 "USER2", dann können nicht $sum 4 $last auf dieser _id. Versuchen Sie es mit compose _id, wenn Sie den Index im Benutzer benötigen.

db.teste.aggregate([
  {$group:{
    _id: {user:"$user",last:"$last"},
    total: {$sum:1},
    last: {
      $sum: {
        $cond:[ {$eq: ["$last", user]}, 1, 0]
      }
    }
  }}
])

Wenn Sie Zeichenfolgen oder andere Vorkommen in verschiedenen Feldern hinzufügen müssen. Abfrage ist:

db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [
      {$group:{
        _id: null,
        user:{$sum:{$cond:[
          {$eq:["$user", "$$indice"]}, 1, 0
        ]}},
        last:{$sum:{$cond:[
          {$eq:["$last", "$$indice"]}, 1, 0
        ]}}
      }},
      {$project:{
        _id: 0
      }}
    ],
    as: "res"
  }}
])

Von Null zum Helden:

//First we'll extract only what we need find, on this case distinct users
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }}
])

//Here we will get the indexes of the search and reinsert in our filter using $let (nodejs var)
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [],
    as: "res"
  }}
])

//Let's counter the total of reinserted elements
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [
      {$group:{
        _id: null,
        total:{$sum:1}
      }}
    ],
    as: "res"
  }}
])

//Now let's test a true condition
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [
      {$group:{
        _id: null,
        user:{$sum:{$cond:[
          {$eq:[true, true]}, 1, 0
        ]}}
      }}
    ],
    as: "res"
  }}
])

//cond tested let's extract what we want
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [
      {$group:{
        _id: null,
        user:{$sum:{$cond:[
          {$eq:["$user", "$$indice"]}, 1, 0
        ]}},
        last:{$sum:{$cond:[
          {$eq:["$last", "$$indice"]}, 1, 0
        ]}}
      }}
    ],
    as: "res"
  }}
])

//Let's take the _id of the sub-colection because we do not need it
db.teste.aggregate([
  {$group:{
    _id: "$user"
  }},
  {$lookup:{
    from: "teste",
    let: { indice: "$_id" },
    pipeline: [
      {$group:{
        _id: null,
        user:{$sum:{$cond:[
          {$eq:["$user", "$$indice"]}, 1, 0
        ]}},
        last:{$sum:{$cond:[
          {$eq:["$last", "$$indice"]}, 1, 0
        ]}}
      }},
      {$project:{
        _id: 0
      }}
    ],
    as: "res"
  }}
])