MongoDB Projektion Geschachtelte Arrays

Habe ich eine Sammlung "Konten", die enthält Dokumente, die ähnlich wie diese Struktur:

{
    "email" : "[email protected]",
    "groups" : [
        {
            "name" : "group1",
            "contacts" : [
                { "localId" : "c1", "address" : "some address 1" },
                { "localId" : "c2", "address" : "some address 2" },
                { "localId" : "c3", "address" : "some address 3" }
            ]
        },
        {
            "name" : "group2",
            "contacts" : [
                { "localId" : "c1", "address" : "some address 1" },
                { "localId" : "c3", "address" : "some address 3" }
            ]
        }
    ]
}

Über

q = { "email" : "[email protected]", "groups" : { $elemMatch: { "name" : "group1" } } }
p = { "groups.name" : 0, "groups" : { $elemMatch: { "name" : "group1" } } }
db.accounts.find( q, p ).pretty()

Werde ich erfolgreich bekommen nur die Gruppe von einem angegebenen Konto bin ich interessiert.

Frage: Wie kann ich eine begrenzte Liste "Kontakte" innerhalb einer bestimmten "Gruppe" einer bestimmten "Konto"? Nehmen wir an ich habe die folgenden Argumente:

  • Konto: E-Mail - "[email protected]"
  • Gruppe: - name - "Gruppe1"
  • Kontakt: array von localIds - [ "c1", "c3", "Nicht existierende id" ]

Gegeben, diese Argumente hätte ich gerne Folgendes Ergebnis:

{
    "groups" : [
        {
            "name" : "group1", (might be omitted)
            "contacts" : [
                { "localId" : "c1", "address" : "some address 1" },
                { "localId" : "c3", "address" : "some address 3" }
            ]
        }
    ]
}

Ich brauche nichts anderes, abgesehen von der daraus resultierenden Kontakte.

Ansätze

Alle Anfragen versuchen zu Holen, nur ein passender Kontakt, anstatt eine Liste der passenden Kontakte, der Einfachheit halber.
Ich habe versucht, die folgenden Abfragen ohne Erfolg:

p = { "groups.name" : 0, "groups" : { $elemMatch: { "name" : "group1", "contacts" : { $elemMatch: { "localId" : "c1" } } } } }
p = { "groups.name" : 0, "groups" : { $elemMatch: { "name" : "group1", "contacts.localId" : "c1" } } }
not working: returns whole array or nothing depending on localId


p = { "groups.$" : { $elemMatch: { "localId" : "c1" } } }
error: {
    "$err" : "Can't canonicalize query: BadValue Cannot use $elemMatch projection on a nested field.",
    "code" : 17287
}


p = { "groups.contacts" : { $elemMatch: { "localId" : "c1" } } }
error: {
    "$err" : "Can't canonicalize query: BadValue Cannot use $elemMatch projection on a nested field.",
    "code" : 17287
}

Jede Hilfe ist willkommen!

  • Ein weiteres für die Zuschauer. Dies ist, wie Sie "Fragen" hier. Zeigen Sie, was Sie versucht haben, und geben Sie bestimmte Fehler. Gute Möglichkeit zu Fragen.
  • Gute Frage.
InformationsquelleAutor cbopp | 2015-03-11
Schreibe einen Kommentar