Search through the collection of references in mongodb

I currently have a model set up in this way:

MyCollection
{
  ...
  groups : [{ type: Schema.Types.ObjectId, ref: 'Group' }],
  ...
}

But I am facing an issue with finding all documents that contain a group with a specific _id. I attempted the following query:

MyCollection.find({
                'groups' : {
                  $elemMatch : {
                    '$ref' : 'Group',
                    '$id'  : myid
                  }
                }
             }).exec(cb);

However, this query is not yielding the desired results and has left me feeling frustrated.

Here is an example of a document:

{ _id: 52d7dd87f3f1e72c7c000005,
   groups: [ { _id: 52d02565360c206933000013, name: 'groupname' } ],
   date: Thu Jan 16 2014 10:15:00 GMT+0200 (EET),
   ...
}

Another attempt was made as follows:

> db.groups.find({ "name" : "NINFOS13"})
{ "_id" : ObjectId("52d8fad69c7817b52a000012"), "createdAt" : ISODate("2014-01- 17T09:41:42.365Z"), "name" : "NINFOS13", "__v" : 0 }
> db.subjects.insert({groups : [ { _id : ObjectId("52d8fad69c7817b52a000012"), name : "NINFOS13"}]})
> db.subjects.find()
{ "_id" : ObjectId("52d8fb7c1c4493a980630c68"), "groups" : [  {  "_id" : ObjectId("52d8fad69c7817b52a000012"),  "name" : "NINFOS13" } ] }
> db.subjects.find({"groups._id" : ObjectId("52d8fb7c1c4493a980630c68")}).count()
0

Upon further inspection, it appears that my previous query did work after all!

Answer №1

Successfully executed in the mongo shell:

> db.stack.insert({groups: [ { _id: ObjectId("52d02565360c206933000013"), name: "groupname" } ]});    

> db.stack.find()
{ "_id" : ObjectId("52d8924b5c90ea648f2a4664"), "groups" : [  {  "_id" : ObjectId("52d02565360c206933000013"),  "name" : "groupname" } ] }

> db.stack.find({"groups._id": ObjectId("52d02565360c206933000013")});
{ "_id" : ObjectId("52d8924b5c90ea648f2a4664"), "groups" : [  {  "_id" : ObjectId("52d02565360c206933000013"),  "name" : "groupname" } ] }

It is possible that there is a typographical error.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with external data in D3.js involves loading and manipulating datasets efficiently

As a newcomer to D3.js, I have been exploring various tutorials and exercises to familiarize myself with it. My primary goal with D3 is to load external data, typically in JSON format, and create interactive charts based on that data. You can find the bas ...

Utilize AngularJS to determine the specific tag to select from a set list of Parse objects

I have a controller in AngularJS that retrieves objects from the backend using Parse: function MyController() { var self = this; var listObjects; function fetchObjects() { var myObject = Parse.Object.extend("MyObject"); var qu ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

ThreeJS | The object's position cannot be cloned as it seems to be undefined, however, this is unexpected

My code problem is not as complex as it seems. The issue lies within the section marked by the "ERROR APPEARS HERE" comments. The error message I am encountering reads: Uncaught TypeError: Cannot read property 'position' of undefined This er ...

What is the best way to update the image card in bootstrap?

Could someone please assist me in changing the image displayed? I keep getting the same copied image, but I would like id 1 to have a different image. This is crucial as I plan to present this for my defense in class. Thank you. let htmlString = ` <di ...

Is the input disabled when clicked on?

To ensure the end-to-end functionality of my application, I have implemented a scenario where upon clicking a spinner button, both Username and Password input fields are disabled before being directed to a new page. My testing methodology involves verif ...

Ways to display a specific section on an HTML page using AngularJS

Main page content <div class="row"> <div class="col-md-3"> link 1 link 2 link 3 . . . </div> </div> <div class="col-md-9"> <div ng-view></div> </div& ...

Is MongoDB cursor used by the MongoRepository class?

Citing a response from the following Stack Overflow thread: @Query("{}") Stream<Alarm> findAllByCustomQueryAndStream(); I'm curious about how this function would perform with a substantial dataset. Does it take advantage of MongoDB&a ...

What is the reason file inputs do not trigger 'input' events, while 'change' events do fire?

Trying out a basic input: <input type="file"/> Noticing that the input event doesn't trigger when a new file is selected: $('input').on('input', function(event){ console.log('input value changed', event.targe ...

Why isn't the angularjs directive setting a value for a specific scope?

This is an example of HTML code: <div ng-controller="main"> <div ng-show="showhide">welcome</div> <div my-directive>click</div> <div ng-click="submit()">submit</div> </div> Here ...

Construct a structure containing the key/value pairs of cells within an HTML table row using JavaScript

I'm completely new to JavaScript so please be patient with me; I'm not even sure if I'm searching for the solution correctly. Despite spending hours googling and experimenting, I still can't get it to work. My issue is related to an HT ...

Is there a way to verify if the window's forward navigation feature is enabled using JavaScript?

How can I implement a functionality that triggers when a user lands on a page, navigates to another page, and then returns to the original page? Is it possible to accomplish this by checking if the forward button is enabled? Are there alternative methods ...

Unable to launch Mongo shell on Ubuntu 17.10 due to compatibility issues

Today's version of MongoDB shell is v3.4.7 Attempting to connect to mongodb://127.0.0.1:27017 2018-05-10T10:54:49.810+0530 W NETWORK [thread1] Failed to establish a connection with 127.0.0.1:27017, when checking the socket for erro ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

Best Practices for Iterating over Nested Objects and Arrays Using ng-repeat

I've been trying to use Angular's ng-repeat, but nothing seems to work for me. I'm attempting to loop through companies.users and display all the first names. Any assistance would be greatly appreciated! Thank you! <div ng-app="app" ng-c ...

React.js button classes in action

I am facing an issue with the active button and couldn't find a solution on stackoverflow. In my store, there are buttons for selecting product characteristics. Currently, I have managed to save one value in the state, but if the attribute category i ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Is it necessary to generate a file for each API in Next.js?

When working with Next.js, it is common practice to create a separate file for each new API endpoint. For example, for the /user endpoint, there would be a user.js file with its own handler, and another one for /user/goldmember. Some may argue that this ...

Methods for altering the color of a div using addEventListener

Why doesn't the color change when I click on the div with the class "round"? Also, how can I implement a color change onclick? var round = document.querySelector(".round"); round.addEventListener("click", function() { round.style.backgroundCol ...

Issue (@websanova/vue-auth): http plugin has not been properly configured in drivers/http/axios.js

I've been working on integrating vue-auth into my laravel-vue application, but I'm encountering some console errors: Error (@websanova/vue-auth): drivers/http/axios.js: http plugin has not been set. Uncaught TypeError: this.plugins.http is u ...