sql >> Database teknologi >  >> NoSQL >> MongoDB

Har brug for et tydeligt antal på flere felter, der blev sammenføjet fra en anden samling ved hjælp af mongodb aggregeringsforespørgsel

Dette burde gøre tricket. Jeg testede det på dit inputsæt og tilføjede bevidst nogle dupeværdier som NYC vises i mere end én DESTINATION for at sikre, at det blev de-duperet (dvs. tydeligt antal som anmodet om). For sjov skal du kommentere alle stadierne, og derefter fjerne kommentarer fra oven og ned for at se effekten af ​​hver fase af pipelinen.

var id = "1";

c=db.foo.aggregate([
// Find a thing:
{$match: {"_id" : id}}

// Do the lookup into the objects collection:
,{$lookup: {"from" : "foo2",
            "localField" : "objectsIds",
            "foreignField" : "_id",
            "as" : "objectResults"}}

// OK, so we've got a bunch of extra material now.  Let's
// get down to just the metaDataMap:
,{$project: {x: "$objectResults.metaDataMap"}}
,{$unwind: "$x"}
,{$project: {"_id":0}}

// Use $objectToArray to get all the field names dynamically:
// Replace the old x with new x (don't need the old one):
,{$project: {x: {$objectToArray: "$x"}}}
,{$unwind: "$x"}

// Collect unique field names.  Interesting note: the values
// here are ARRAYS, not scalars, so $push is creating an
// array of arrays:
,{$group: {_id: "$x.k", tmp: {$push: "$x.v"}}}

// Almost there!  We have to turn the array of array (of string)
// into a single array which we'll subsequently dedupe.  We will
// overwrite the old tmp with a new one, too:
,{$addFields: {tmp: {$reduce:{
    input: "$tmp",
    initialValue:[],
    in:{$concatArrays: [ "$$value", "$$this"]}
        }}
    }}

// Now just unwind and regroup using the addToSet operator
// to dedupe the list:
,{$unwind: "$tmp"}
,{$group: {_id: "$_id", uniqueVals: {$addToSet: "$tmp"}}}

// Add size for good measure:
,{$addFields: {size: {"$size":"$uniqueVals"}} }
          ]);


  1. Hadoop RecordReader Introduktion, arbejde og typer

  2. Indstil små filer i ShardingTest

  3. Symfony (PHP framework) og MongoDB (eller enhver json-baseret database)

  4. Hvordan implementerer man ASP.NET Core 3.1 Identity med MongoDB?