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

Mongodb $opslag med indlejret dokument

Du kan bruge nedenstående aggregering med mongodb 3.6 og derover

db.User.aggregate([
  { "$lookup": {
    "from": "orderTracking",
    "let": { "userId": "$userId" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$userId", "$$userId"] }}},
      { "$unwind": "$TrackLocation" },
      { "$lookup": {
        "from": "locationType",
        "let": { "location": "$TrackLocation.locationId" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$locationId", "$$location"] }}}
        ],
        "as": "locationType"
      }},
      { "$project": {
        "_id": 0,
        "productTypeName": { "$arrayElemAt": ["$locationType.productTypeName", 0] },
        "at": "$TrackLocation.at"
      }}
    ],
    "as": "locationType"
  }},
  { "$replaceRoot": { "newRoot": { "$mergeObjects": ["$addres", "$$ROOT"] }}},
  { "$project": { "addres": 0 }}
])

Output

[
  {
    "_id": ObjectId("59a504eb6171b554c02292a9"),
    "city": "Bengaluru",
    "country": "India",
    "dateOfBirth": "1992-01-01",
    "locationType": [
      {
        "at": "2017-10-11",
        "productTypeName": "Warehouse"
      },
      {
        "at": "2017-10-13",
        "productTypeName": "On Transit"
      }
    ],
    "state": "Karnataka",
    "userId": 12,
    "userName": "Shahabaz Shafi"
  }
]



  1. Kan ikke slå TXT-posten op for værten Cluster0-XXXXX.mongodb.net

  2. Min validering virker ikke i Mongoose

  3. Garanterer MongoDB journaling holdbarhed?

  4. Sådan udføres jokertegnssøgning i MongoDB ved hjælp af Java