0

I have a collection called "User". I'm passing userid to get the record. In addition to that i also need additional 10 last updatedAt(DateTime) record excluding the userid record but added together. So, total returned result will be 11 in this case. Is that possible using same query? I tried using Or and lookup but can't make it work as expected. Any help is appreciated.

 User collection:
[{
     "id" : "123456", 
    "name" : "foo", 
    "addressIds" : [ObjectId(234567)]
  }     ,
    "id" : "345678", 
    "name" : "bar", 
    "addressIds" : [ObjectId(678565), ObjectId(567456)]
   }]

 Address collection:
 [{
 "_id":"234567",
 "district" : "district1", 
 "pincode" : "568923",
  },
  {
 "_id":"678565",
 "district" : "district2", 
 "pincode" : "568924",
  },
  {
 "_id":"567456",
 "district" : "district3", 
 "pincode" : "568925",
 }]

Using facets, i have the User and the addressIds. Can i have the actual documents for AddressIds in User?

1

1 Answer 1

1

Edit: You can use $facet, like this:

db.collection.aggregate([
  {$sort: {date: -1}},
  {$facet: {
      byTate: [{$limit: 10}],
      byUser: [{$match: {userId: 455845}}]
    }
  },
  {$project: {
    byDate: {
        $filter: {
            input: "$byDate",
            as: "item",
            cond: {$ne: ["$$item",{"$arrayElemAt": ["$byUser", 0]}]}
        }
    },
    byUser: 1,
    }
  },
  {
    $project: {
      byDate: {$slice: ["$byDate", 10]},
      byUser: 1
    }
  }
])

You can see it works on the playground .

Switch between userId: 455845 / 455845 to see both cases.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the response. This is what i'm looking for. Only question is how do i get the distinct record? Meaning, userId may be inside the bydate result but i want the distinct byDate to not have userId in it.
Answer is edited
I have the required document through facets. I need to get the details from another collection using the reference Ids that i have from facets. Is it possible to use lookup inside facets on single query?
According to the docs no problem.
I have added the sample. I'm able to do this using compass. I used lookup first to get the address inside the User and then use facets to filter the Ids and get 10 more record as you have shown. But i'm not able to do this in C#.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.