Mongoose Aggregation match an array of objectIds - node.js

I have a schema that Looks like this
var Post = new mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
created: {
type: Date,
Default: Date.now
})
I have a User Table as well. I Have a array of user ids and i am trying to search the post table based on an array of user ids
For Example
var userIds = ["575e96652473d2ab0ac51c1e","575e96652473d2ab0ac51c1d"] .... and so on
I want to return all posts created by these users. And posts should be sorted by their creation date. Is there a way to group this post based on the user ids provided, basically match the posts for an individual user?
The result I am trying to attain is something like this:
[{
userAId : "56656.....",
post : [postA, postB],
},{
userBId :"12345...",
post : [postA, postB]
}]
How do I write this query?
This is what I have so far
Post.aggregate([{
// {"$unwind" : ""},
// "$group": {
// _id: "$author",
// "created" : {"$sum" : 1 }
// }
"$match" : { author : id}
}]).exec(function(error, data) {
if(error){
return console.log(error);
}else{
return console.log(data)
}
})
{
"_id" : ObjectId("575e95bc2473d2ab0ac51c1b"),
"lastMod" : ISODate("2016-06-13T11:15:08.950Z"),
"author" : ObjectId("575dac62ec13010678fe41cd"),
"created" : ISODate("2016-06-13T11:15:08.947Z"),
"type" : "photo",
"end" : null,
"commentCount" : 0,
"viewCount" : 0,
"likes" : 0,
"tags" : [],
"title" : "Today is a good day",
"__v" : 0
}

To return all posts created by users depicted in a list of ids, use the $in operator in your query and then chain the sort() method to the query to order the results by the created date field:
Post.find({ "author": { "$in": userIds } })
.sort("-created") // or .sort({ field: 'asc', created: -1 });
.exec(function (err, data){
if(err){
return console.log(err);
} else {
return console.log(data);
}
});
To get a result where you have the post id's grouped per user, you need to run the following aggregation operation:
Post.aggregate([
{ "$match" : { "author": { "$in": userIds } } },
{ "$sort": { "created": -1 } },
{
"$group" : {
"_id" : "$author",
"posts" : { "$push": "$_id" }
}
},
{
"$project": {
"_id": 0,
"userId": "$_id",
"posts": 1
}
}
]).exec(function (err, result){
if(err){
return console.log(err);
} else {
return console.log(result);
}
});
Or with the fluent API:
Post.aggregate()
.match({ "author": { "$in": userIds } })
.sort("-created")
.group({
"_id" : "$author",
"posts" : { "$push": "$_id" }
})
.project({
"_id" : 0,
"userId" : "$_id",
"posts": 1
})
.exec(function (err, result){
if(err){
return console.log(err);
} else {
return console.log(result);
}
});

This should be possible without aggregation.
Post
.find({ author: { $in: userIds } })
.sort({ created: -1 })
If you get CastError: Cast to ObjectId failed, make sure to map your userIds array from an array of strings to an array of mongoose id's.
userIds = userIds.map(userId => new mongoose.Types.ObjectId(userId))

Related

How to update multiple documents?

I want to update multiple documents.
My current Document,
Document Account
{
"_id" : "5cbd96aca1a6363473d4g8745",
"contact" : [
"5cbd96aca1a6363473d4a968",
]
},
{
"_id" : "5cbd96aca1a6363473d4g8746",
"contact" : [
"5cbd96aca1a6363473d4z7632",
]
}
I need below output,
update contact array with different _id.
Document Account
{
"_id" : "5cbd96aca1a6363473d4g8745",
"contact" : [
"5c98833f98770728a7047f1a",
"5cbd96aca1a6363473d4a968",
]
},
{
"_id" : "5cbd96aca1a6363473d4g8746",
"contact" : [
"5caddf78b8c0645402090536",
"5cbd96aca1a6363473d4z763",
]
}
Use $addToSet or $push to push id with bulk update.
You can use update with upsert. It will update the doc if exist and if not then it will create new one.
for example:
//Make a obj to set
var contacts = {
id: req.body.id,
contactIds: req.body.contactIds,
};
req.app.db.models.ModelsName.update(
{
//if you want multiple fields to be update
$and: [{ id: contacts.id }, { contactIds: { $in: contacts.contactIds } }]
},
//Set the above obj
{ $set: contacts },
{ upsert: true },
(err, result) => {
if (err) {
console.log(err.message)
}
console.log("Updated successfully")
})
This is just a reference. Modify accordingly your use.
You can use Bulk.find.update() method to update all matching documents.
example:
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).update( { $set: { item: "TBD" } } );
bulk.execute();

Mongodb | Romove object from document's array

I tried to remove an object from document array but something not working:
This is my object:
{
"_id" : ObjectId("5b487aa1427e5a1edc1cdbac"),
"location" : {
"latitude" : 0,
"longitude" : 0
},
"email" : "ran#gmail.com",
"firstName" : "Ran",
"lastName" : "Alcobi",
"interests" : [
ObjectId("5b49a44bc3b19929b098547e")
],
}
I removed Interest from the interests collection and I need that the interest will be removed from the Interests array of the user:
this is my code:
router.delete('/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Interest.findOneAndRemove({
_id: id,
}).then((interest) => {
if (!interest) {
return res.status(404).send();
}
User.update(
{$pull:
{interests: {$in : interest._id} }
},
{multi: true},
).then((user) => {
console.log(user);
res.send({interest});
}).catch((e) => {
res.status(400).send();
});
});
});
Thanks a lot for helpers. I would be happy to know what is my mistake.
You are passing $pull in wrong parameter of update query... In update query first parameter is for filter and second parameter is for update operation... So you have to first filter with $in and then $pull from the interest array...
So, finally you need to do something like this
User.update(
{ interests: { $in : [interest._id] } },
{ $pull: { interests: interest._id } }
{ multi: true },
)

If condition query for mongo db

I have an collection with documents that can be public or private. I am looking to have a single query that can get a document by an _id and check if it's private. If it is private it needs to check if the user requesting the document is a participant in the object.
Here is the object:
{
"_id" : ObjectId("5769ae620e80ea1c7f8a997f"),
"owner" : ObjectId("5740edae95a1b4c043d033df"),
"private" : false,
"participants" : [
{
"uid" : ObjectId("5740edae95a1b4c043d033df"),
"notify" : true
}
],
"messages" : [ ]
}
This is the 2 step query I wrote and wondering if I can simplify it
function getRoom(roomId, user){
db.rooms.findOne({ _id: pmongo.ObjectId(roomId) })
.then(room => {
if(room.private){
return db.rooms.findOne({
_id: pmongo.ObjectId(roomId),
participants: {$eleMatch: {uid: String(user._id)}}
})
} else {
return room
}
})
}
Any help would be great!
MongoDB has $or operator which can be used in this case:
db.rooms.findOne({ $or: [
{
_id: pmongo.ObjectId(roomId),
private: { $ne: true }
}, {
_id: pmongo.ObjectId(roomId),
participants: {$eleMatch: {uid: String(user._id)}}
}
]})

Sort Embedded Documents in Array and fetch specifics

I have a mongoose model like this:
var activityItem = mongoose.Schema({
timestampValue: Number,
xabc: String,
full: Boolean,
comp: Boolean
});
var ABC = mongoose.Schema({
activity: [activityItem],
user: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
username: String
});
I want to get the activityItem array elements that have a timestampValue less than a specific value. Also, I want to sort the activity array first according to the timestampValue
This is the code that I currently have. And it doesn't work.
UserActivity.findOne({
'user': current_user,
'activity' : {
$all: [
{
"$elemMatch": {
timestampValue: {
$lte: time
}
}
}
]
}
},
function(err, user){
})
Sample Document structure:
{
"_id" : ObjectId("56d5e88adfd14baf1848a7c6"),
"user" : ObjectId("56bf225342e662f4277ded73"),
"notifications" : [],
"completed" : [],
"activity" : [
{
"timestampValue": 1456902600000,
"xabc": "Some value",
"full": true,
"comp": false,
"_id" : ObjectId("56d5e88adfd14baf1848a7d2")
},
{
"timestampValue": 1456702600000,
"xabc": "Some other value",
"full": true,
"comp": false,
"_id" : ObjectId("56d5e88adfd14baf1848a7d3")
}
],
"__v" : 1
}
The POST call has the following params
hash: "2e74aaaf42aa5ea733be963cb61fc5ff"
time: 1457202600000
hash comes into the picture once i have the docs from mongo
time is a unix timestamp value.
Instead of returning only the elements that are less than the time value, it is returning all the array elements. I tried the aggregation framework to sort the array before querying, but couldn't get the hang of it.
Any help would be greatly appreciated.
Please try to do it through aggregation as below
ABS.aggregate([
// filter the document by current_user
{$match: {user: ObjectId(current_user)}},
// unwind the activity array
{$unwind: '$activity'},
// filter the timestampValue less than time
{$match: {'activity.timestampValue': {$lte: time}}},
// sort activity by timestampValue in ascending order
{$sort: {'activity.timestampValue': 1}},
// group by _id, and assemble the activity array.
{$group: {_id: '$_id', user: {$first: '$user'},activity: {$push: '$activity'}}}
], function(err, results){
if (err)
throw err;
// populate user to get details of user information if needed
//ABS.populate( results, { "path": "user" }, function(err, rets) {
//
//});
});
Well, it seems little bit tricky with MongoDb aggregation pipeline unless you have MongoDB 3.2, but you can definitely
achieve your result with help of map-reduce.
e.g.
MongoDB version < 3.2
var findActivities = function (time) {
db.col.mapReduce(function () {
var item = Object.assign({}, this);
delete item.activity;
item.activity = [];
for (var i = 0; i < this.activity.length; i++) {
if (this.activity[i].timestampValue <= time) {
item.activity.push(this.activity[i]);
}
}
emit(item._id, item);
}, function (k, v) {
return {items: v};
}, {
out: {"inline": true},
scope: {time: time}
}).results.forEach(function (o) {
printjson(o); // Or perform action as appropriate
});
};
Based your sample data when called findActivities(1456802600000), it will find and return only those documents matching criteria.
{
"_id" : ObjectId("56d5e88adfd14baf1848a7c6"),
"value" : {
"_id" : ObjectId("56d5e88adfd14baf1848a7c6"),
"user" : ObjectId("56bf225342e662f4277ded73"),
"notifications" : [
],
"completed" : [
],
"__v" : NumberInt(1),
"activity" : [
{
"timestampValue" : NumberLong(1456702600000),
"xabc" : "Some other value",
"full" : true,
"comp" : false,
"_id" : ObjectId("56d5e88adfd14baf1848a7d3")
}
]
}
}
MongoDB version 3.2+
db.col.aggregate([
{$project:{user:1, notifications:1, completed:1, activity:{
$filter:{input: "$activity", as: "activity", cond:{
$lte: ["$$activity.timestampValue", 1456802600000]}}}}}
])
Both solutions will have same output.

Mongoose : associate a .project (aggregation) with .find().limit().sort() etc

I have a mongoose Schema looking like this :
var AnswerSchema = new Schema({
author: {type: Schema.Types.ObjectId, ref: 'User'},
likes: [{type: Schema.Types.ObjectId, ref: 'User'}],
date: {type: Date, default: Date.now},
text: String,
....
});
As of now, I query this collection by doing this :
Answer.find({
author: profileId,
date: {$lt: fromDate}
}).sort({date: -1})
.limit(25)
.populate('question.sender', 'username username_display name')
.exec(function (err, answers) {
*code here*
});
But I need to add a computed field in this query to know if the visitor already liked the answers of an author (see this question) thanks to the aggregation pipeline. It would look like this :
Answer.aggregate()
.project({
"author": 1,
"matched": {
"$eq": [
{
"$size": {
"$ifNull": [
{ "$setIntersection": [ "$likes", [userId] ] },
[]
]
}
},
1
]
}
})
.exec(function (err, docs){
console.log(docs);
})
Problem is : I need to run this projection on the documents filtered by the first query only. In other words, I need to combine the find/limit/sort, with the project.
How could I do this ? I've tried chaining the .project() after the first query (before the .exec()), but it doesn't work. Maybe I need to do all the things I do in the first query via the aggregation chain of mongodb ?
EDIT:
Here is an example of data-set to try this :
{
"_id" : ObjectId("56334295e45552c018fc475d"),
"author" : ObjectId("561f9c319cdd94401ae160ef"),
"likeCount" : 1,
"likes" : [
ObjectId("561f9c319cdd94401ae160ef")
],
"text" : "This is the answer content",
"question" : {
"questionId" : ObjectId("56334031e45552c018fc4757"),
"sender" : ObjectId("561f9c319cdd94401ae160ef"),
"date" : ISODate("2015-10-30T10:02:25.323Z")
},
"date" : ISODate("2015-10-30T10:12:37.894Z")
},
{
"_id" : ObjectId("563246cfa04c1b281b6d97bf"),
"author" : ObjectId("561f9c319cdd94401ae160ef"),
"likeCount" : 0,
"likes" : [],
"text" : "Bla bla bla",
"question" : {
"questionId" : ObjectId("562f9a74a16d6fb418752b37"),
"sender" : ObjectId("561f9c319cdd94401ae160ef"),
"date" : ISODate("2015-10-27T15:38:28.337Z")
},
"date" : ISODate("2015-10-29T16:18:23.020Z")
}
Use the aggregate fluent API's chaining methods match(), sort() + limit() before the project() method:
Answer.aggregate()
.match({
"author": profileId,
"date": { "$lt": fromDate }
})
.sort("-date")
.limit(25)
.project({
"author": 1, "question.sender": 1,
"matched": {
"$eq": [
{
"$size": {
"$ifNull": [
{ "$setIntersection": [ "$likes", [userId] ] },
[]
]
}
},
1
]
}
})
.exec(function (err, docs){
if (err) throw err;
console.log(docs);
var answers = docs.map(function(doc) { return new Answer(doc); });
Answer.populate(answers, {
"path": "question.sender",
"select": "username username_display name"
}, function(err, results) {
if (err) throw err;
console.log(JSON.stringify(results, undefined, 4 ));
res.json(results);
});
});

Resources