Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

aggregation framework - how to use lookup along with $push in mongodb

I was playing with Mongodb and wanted a query that use lookup and $push or $addToSet

See this https://mongoplayground.net/p/4hSPKW_bCdM

How can i make this query correct. do we need loop over here ?

Should return

{
  "response": [
    {
      "_id": "5fcdcc14da26c80a6de06754",
      "first_name": "James",
      "last_name": "Hales",
      "username": "jim",
      "timestamp": 1607322644202,
      "userData": [
        {
          "_id": "6011021851781d3d9841e09d",
          "user_id": "5fcdcc14da26c80a6de06754",
          "photo": [
            {
              "_id": "6011021851781d3d9841e09e",
              "url": "http://localhost:3000/files/ou93r0cfjde0cat.jpg",
              "width": 250,
              "height": 500,
              "preview": "skjdfbsdjvns;svnsdvisdvnvsdjvnsdivsdkvsdivsdjvnsdjvsdvsdvgjsvnsvhi"
            }
          ],
          "status": "Active",
          "timestamp": 1611727384083,
          "expire_at": "2021-01-27T06:03:04.083Z"
        },
        {
          "_id": "6011021851781d3d9841e09d",
          "user_id": "5fcdcc14da26c80a6de06754",
          "photo": [
            {
              "_id": "6011021851781d3d9841e09e",
              "url": "http://localhost:3000/files/ou93r0cfjee0bat.jpg",
              "width": 250,
              "height": 500,
              "preview": "skjdfbsdjvns;svnsdvisdvnvsdjvnsdivsdkvsdivsdjvnsdjvsdvsdvgjsvnsvhi"
            }
          ],
          "status": "Active",
          "timestamp": 1611727384083,
          "expire_at": "2021-01-27T06:03:04.083Z"
        }
      ]
    }
  ]
}

Thank in advance

question from:https://stackoverflow.com/questions/65915319/how-to-use-lookup-along-with-push-in-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • (optional) $match user id in array or not
  • $lookup with site, pass _id as localfield and user_id as foreignfield
  • (optional) $match if you want to remove empty userData user's document
db.users.aggregate([
  // optional match stage
  {
    $match: {
      _id: { $in: [ObjectId("5fcdcc14da26c80a6de06754"), ObjectId("5fcdd0075dc42a0d5c7ec813")] }
    }
  }
  {
    $lookup: {
      from: "site",
      localField: "_id",
      foreignField: "user_id",
      as: "userData"
    }
  },
  // optional match stage
  { $match: { userData: { $ne: [] } } }
])

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...