I've got a Mongo DB doc with a teams array. All the objects in the teams array contain a user_ids array. How do I find all documents containing a team where user_ids contains a specific Object Id? I'm using Mongoose with Node.
This is the doc structure. How would I eg find all docs with Object Id "56a60da2351195cc6be83799" in any of the teams?
{
"_id" : ObjectId("56a60da3351195cc6be8379c"),
"session_id" : ObjectId("56a60da2351195cc6be83798"),
"teams" : [
{
"score" : 0,
"user_ids" : [
ObjectId("56a60da2351195cc6be83799")
]
},
{
"score" : 0,
"user_ids" : [
ObjectId("56a60da2351195cc6be8379a")
]
}
],
"created_at" : ISODate("2016-01-25T11:57:23.006Z") }
Thanks
Let's say your collection name is collection, try:
db.collection.find({"teams.user_ids": ObjectId("56a60da2351195cc6be83799")})
It will find a document, if exists matching user_ids
For nested arrays the $in operator will be a good choice (see documentation).
I tried to reproduce your settings and created a simple model:
var testSchema = mongoose.Schema({
session_id: { type: Number },
teams : [
{
score: { type: Number },
user_ids: [{ type: Number }]
}
]
})
var Test = mongoose.model("Test", testSchema);
Inserted demo data:
var test1 = new Test({
session_id: 5,
teams: [
{ score: 5, user_ids: [ 1, 2, 4] },
{ score: 3, user_ids: [ 2, 7, 9 ] },
{ score: 1, user_ids: [ 3 ] },
]
});
test1.save(function(err, t1) { console.log("test", err, t1); });
var test2 = new Test({
session_id: 1,
teams: [
{ score: 5, user_ids: [ 11, 12 ] },
{ score: 3, user_ids: [ 1, 9 ] },
]
});
test2.save(function(err, t2) { console.log("test", err, t2); });
The query to get all objects with a userId of 2 would look like:
Test.find({ "teams.user_ids": { $in: [2] }}, function(err, res) {
console.log("query:", err, res);
});
Or in a more mongoose way of reassembling queries:
Test.find()
.where('teams.user_ids')
.in([2])
.then(result => { console.log(result); })
.catch(err => { console.log(err); });
Related
I have a collection of users that has an array of multiple plates :
users : [
{
_id: '61234XXX'
plates: [
{
_id: '123'
'color': 'orange'
},
{
_id: '124'
'color': 'blue'
}
]
},
{
_id: '63456XXX'
plates: [
{
_id: '321'
'color': 'orange'
},
{
_id: '432'
'color': 'green'
}
]
}
]
I'm trying to figure out a way to add a new field to the all current plate objects for every user:
I've got to this:
await User.findOneAndUpdate(
{ _id: '63456XXX' },
{
$set : {
[`plates.0.plateStyle`]: "testValue"
}
}
)
Tho this works it's not fit for purpose. Is there a better way I can iterate over this?
You can try this query:
Here you are using array filters to tell mongo: "Where you find an object with _id: "61234XXX" and exists the plates then, there, get the document (elem) which match that plates is not empty (to get all) and add plateStyle".
await User.updateMany({
_id: "61234XXX",
plates: {
$exists: true
}
},
{
$set: {
"plates.$[elem].plateStyle": "testValue"
}
},
{
arrayFilters: [
{
elem: { $ne: [ "$plates", [] ] }
}
]
})
Example here
Also if you are finding by _id you won't need updateMany since _id is unique and only will be 1 or 0 results.
this is my first time asking in StackOverflow and I hope I can explain what I'm aiming for.
I've got documents that look like this:
"_id" : ObjectId("5fd76b67a7e0fa652a297a9f"),
"type" : "play",
"session" : "5b0b5d57-c3ca-415f-8ef6-49bbd5805a23",
"episode" : 1,
"show" : 1,
"user" : 1,
"platform" : "spotify",
"currentTime" : 0,
"date" : ISODate("2020-12-14T13:40:51.906Z"),
"__v" : 0
}
I'd like to fetch for a show and group them by episode. I've got this far with my aggregattion:
const filter = { user, show, type: { $regex: /^(play|stop|close)$/ } }
const requiredFields = { "episode": 1, "session": 1, "date": 1, "currentTime": 1 }
// Get sessions grouped by episode
const it0 = {
_id: '$episode',
session:
{$addToSet:
{_id: "$session",
date:{$dateToString: { format: "%Y-%m-%d", date: "$date" }},
averageOfSession: {$cond: [ { $gte: [ "$currentTime", 0.1 ] }, "$currentTime", null ] }
},
},
count: { $sum: 1 }
}
// Filter unique sessions by session id and add them to a sessions field
const reduceSessions = {$addFields:
{sessions: {$reduce: {input: "$session",initialValue: [],in:
{$concatArrays: ["$$value",{$cond: [{$in: ["$$this._id","$$value._id"]},[],["$$this"]]}]}
}}}}
const projection = { $project: { _id: 0, episode: "$_id", plays: {$size: '$sessions'}, dropoff: {$avg: "$sessions.averageOfSession"}, sessions: '$session.date', events: "$count" } }
const arr = await Play.aggregate([
{ $match: filter }, {$project: requiredFields}, {$group: it0}, reduceSessions,
projection,{ $sort : { _id : 1 } }
])
and this is what my result looks like so far:
{
"episode": 5,
"plays": 4,
"dropoff": 3737.25,
"sessions": [
"2020-11-15",
"2020-11-15",
"2020-11-16",
"2020-11-15"
],
"events": 4
}...
What I'd like is for the 'sessions' array to be an object with one key for each distinct date which would contain the count, so something like this:
{
"episode": 5,
"plays": 4,
"dropoff": 3737.25,
"sessions": {
"2020-11-15": 3,
"2020-11-16": 1
},
"events": 4
}...
Hope that makes sense, thank you!!
You can first map sessions into key-value pairs. Then $group them to add up the sum. Then use $arrayToObject to convert to the format you want.
This Mongo playground is referencing this example.
I have the following schema:
let PlayerSchema = new mongoose.Schema( {
name: String,
country: String,
roundResults: [ {
round: Number,
result: String,
points: Number
} ]
} );
When I use findOneAndUpdate to update a document:
Player.findOneAndUpdate({ id: req.params.id },
{$push: {"roundResults": result }},
{safe: true, upsert: true, new : true},
(err, player) => {
if( ! err && player ) {
res.json( player );
} else {
res.json( err );
}
}
);
I get the following unexpected result:
[
{
"_id": "57c9eb55c2a07a401462e3ec",
"name": "Joe Bloggs",
"country": "England",
"__v": 0,
"roundResults": [
{
"_id": "57c9eba11c597d5e1460e4f0"
}
]
}
]
I don't have a roundResults schema but, I get an _id as shown above, I would expect to see,:
"roundResults": [
"round": 1,
"result": "1",
"points": 3
]
Can anyone explain why this is, or how I get this to nest the data I am displaying directly above?
Even if you pass literal object for sub documents, it is a Schema. And id would be generated for that. If it is an array define its type Array.
Attention that if you define any schema for a property it is considered as a subdoc and entity so it has id
I have two Mongoose schemas:
var EmployeeSchema = new Schema({
name: String,
servicesProvided: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Service'
}]
});
var ServiceSchema = new Schema({
name: String
});
I'm trying to find employees who provide a specified service with the service ID I send into the http request. This is my code:
Employee
.find({
servicesProvided: req.params.service_id
})
.exec(function(err, employees) {
if (err) {
console.log(err);
res.send(err);
} else {
res.json(employees);
}
});
The problem is that this code returns an empty array and I don't know why. I've tried a lot of things like casting the service id to mongoose.Schema.Types.ObjectId but it doesn't work.
Any idea? I'm using Mongoose 3.8.39. Thanks!
In your EmployeeSchema, servicesProvided is an array, to filter employees by that field you should use $in operator:
var services = [req.params.service_id];
Employee.find({
servicesProvided: {
$in: services
}
}, ...
I think you need $elemMatch! From docs:
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] },
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] },
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
Search like:
db.survey.find({ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } })
Results in:
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }
But since you're doing a single query condition (look at the docs again) you can replace
db.survey.find(
{ results: { $elemMatch: { product: "xyz" } } }
)
with
db.survey.find(
{ "results.product": "xyz" }
)
So in your case it should be something like:
find({
'servicesProvided': ObjectId(req.params.service_id)
})
Schema Definitions
Team.js
var TeamSchema = new Schema({
// Team Name.
name: String,
lead: String,
students :type: [{
block : Number,
status : String,
student : {
type: Schema.ObjectId,
ref: 'Student'
}]
});
Student.js
var StudentSchema = new Schema({
name: String,
rollNo : Number,
class : Number
});
How I can populate "student" to get output, as below:
team
{
"__v": 1,
"_id": "5252875356f64d6d28000001",
"students": [
{
"__v": 1,
"_id": "5252875a56f64d6d28000002",
block : 1,
status : joined,
"student": {
"name": Sumeeth
"rollNo" : 2
"class" : 5
}
},
{
"__v": 1,
"_id": "5252875a56f64d6d28000003",
block : 1,
status : joined,
"student": {
"name": Sabari
"rollNo" : 3
"class" : 4
}
}
],
"lead": "Ratha",
}
This is JS I use to get the document using Mongoose:
Team.findOne({
_id: req.team._id
})
.populate('students')
.select('students')
.exec(function(err, team) {
console.log(team);
var options = {
path: 'students.student',
model: 'Student'
};
Student.populate(team.students,options,function(err, students) {
console.log(students);
if (err) {
console.log(students);
res.send(500, {
message: 'Unable to query the team!'
});
} else {
res.send(200, students);
}
});
});
In my console output I get the following:
{ _id: 53aa434858f760900b3f2246,
students
[ { block : 1
status: 'joined'
_id: 53aa436b58f760900b3f2249 },
{ block : 1
status: 'joined'
_id: 53aa436b58f760900b3f2250 }]
}
And the expected output is:
{ _id: 53aa434858f760900b3f2246,
students
[ { block : 1
status: 'joined'
student :{
"name": Sumeeth
"rollNo" : 2
"class" : 5
}
},
{ block : 1
status: 'joined'
student :{
"name": Sabari
"rollNo" : 3
"class" : 4
}
}
]
}
Some one please help me where I am wrong. How should I make use of .populate, so that , I can get the entire student object and not only its id.
Reference :
Populate nested array in mongoose
I have been facing same issue. I have use this code for my rescue :
Team.findOne({_id: req.team._id})
.populate({ path: "students.student"})
.exec(function(err, team) {
console.log(team);
});
Here is a simplified version of what you want.
Basic data to set up, first the "students":
{
"_id" : ObjectId("53aa90c83ad07196636e175f"),
"name" : "Bill",
"rollNo" : 1,
"class" : 12
},
{
"_id" : ObjectId("53aa90e93ad07196636e1761"),
"name" : "Ted",
"rollNo" : 2,
"class" : 12
}
And then the "teams" collection:
{
"_id" : ObjectId("53aa91b63ad07196636e1762"),
"name" : "team1",
"lead" : "me",
"students" : [
{
"block" : 1,
"status" : "Y",
"student" : ObjectId("53aa90c83ad07196636e175f")
},
{
"block" : 2,
"status" : "N",
"student" : ObjectId("53aa90e93ad07196636e1761")
}
]
}
This is how you do it:
var async = require('async'),
mongoose = require('mongoose');
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/team');
var teamSchema = new Schema({
name: String,
lead: String,
students: [{
block: Number,
status: String,
student: {
type: Schema.ObjectId, ref: 'Student'
}
}]
});
var studentSchema = new Schema({
name: String,
rollNo: Number,
class: Number
});
var Team = mongoose.model( "Team", teamSchema );
var Student = mongoose.model( "Student", studentSchema );
Team.findById("53aa91b63ad07196636e1762")
.select('students')
.exec(function(err, team) {
console.log( team );
async.forEach(team.students, function(student,callback) {
Student.populate(
student,
{ "path": "student" },
function(err,output) {
if (err) throw err;
callback();
}
);
},function(err) {
console.log( JSON.stringify( team, undefined, 4 ) );
});
});
And it gives you the results:
{
"_id": "53aa91b63ad07196636e1762",
"students": [
{
"block": 1,
"status": "Y",
"student": {
"_id": "53aa90c83ad07196636e175f",
"name": "Bill",
"rollNo": 1,
"class": 12
}
},
{
"block": 2,
"status": "N",
"student": {
"_id": "53aa90e93ad07196636e1761",
"name": "Ted",
"rollNo": 2,
"class": 12
}
}
]
}
You really do not need the "async" module, but I am just "in the habit" as it were. It doesn't "block" so therefore I consider it better.
So as you can see, you initial .populate() call does not do anything as it expects to "key" off of an _id value in the foreign collection from an array input which this "strictly speaking" is not so as the "key" is on "student" containing the "foreign key".
I really did cover this in a recent answer here, maybe not exactly specific to your situation. It seems that your search did not turn up the correct "same answer" ( though not exactly ) for you to draw reference from.
You are overthinking it. Let Mongoose do the work for you.
Team.findOne({
_id: req.team._id
})
.populate({path:'students'})
.exec(function(err, team) {
console.log(team);
});
This will return students as documents rather than just the ids.
TL DR
const team = await Team.findById(req.team._id)
.populate("students");
team.students = await Student.populate(team.students, {path: "student"});
Context
Reading from all the answers I went testing everything and just Neil Lun's answer worked for me. The problem is it was on the path to a cb hell. So I cracked my head a little and 'refactored' to an elegant one-liner.
const foundPost = await Post.findById(req.params.id)
.populate("comments")
.populate("author");
foundPost.comments = await User.populate(foundPost.comments, {path: "author"});
My initial problem:
{
title: "Hello World",
description: "lorem",
author: {/* populated */},
comments: [ // populated
{text: "hi", author: {/* not populated */ }}
]
};
How my models basically are:
User = {
author,
password
};
Post = {
title,
description,
author: {}, //ref User
comments: [] // ref Comment
};
Comment = {
text,
author: {} // ref User
};
The output after problem solved:
{
comments: [
{
_id: "5dfe3dada7f3570b60dd977f",
text: "hi",
author: {_id: "5df2f84d4d9fcb228cd1df42", username: "jo", password: "123"}
}
],
_id: "5da3cfff50cf094c68aa2a37",
title: "Hello World",
description: "lorem",
author: {
_id: "5df2f84d4d9fcb228cd1aef6",
username: "la",
password: "abc"
}
};