0

I am trying to check If a field exists in a sub-document of an array and if it does, it will only provide those documents in the callback. But every time I log the callback document it gives me all values in my array instead of ones based on the query.

I am following this tutorial And the only difference is I am using the findOne function instead of find function but it still gives me back all values. I tried using find and it does the same thing.

I am also using the same collection style as the example in the link above.

Example enter image description here In the image above you can see in the image above I have a document with a uid field and a contacts array. What I am trying to do is first select a document based on the inputted uid. Then after selecting that document then I want to display the values from the contacts array where contacts.uid field exists. So from the image above only values that would be displayed is contacts[0] and contacts[3] because contacts1 doesn't have a uid field.

Contact.contactModel.findOne({$and: [

        {uid: self.uid},

        {contacts: {

          $elemMatch: {

            uid: {

              $exists: true,

              $ne: undefined,

            }

          }

        }}

      ]}
Jagr
  • 484
  • 2
  • 11
  • 31
  • Please try to update the link for the tutorial, its not correct. – HPCS Oct 05 '19 at 15:07
  • I apologize and its updated – Jagr Oct 05 '19 at 15:13
  • That link is not a tutorial and the problems stem from the data model. While you _can_ embed data you would have to look up in a RDBMS, it is only reasonable to do so in OneTo(Very)Few™ relations. If I find the time later this day, I would come up with an alternate data model and a solution for the use case. What are the uids for? You already have an `_id`. – Markus W Mahlberg Oct 05 '19 at 17:21
  • THe **uid** is the users _id. So in another collection I store user data and this is there "contacts" from their phone book. – Jagr Oct 05 '19 at 17:30
  • So, there is no semantic difference, as you could use the `_id` for this as well. Gotcha. – Markus W Mahlberg Oct 05 '19 at 18:09
  • @Jagr See my answer. The whole uid thing is quite unnecessary. And you can simplify your queries a great deal. – Markus W Mahlberg Oct 05 '19 at 18:57
  • Ah thank you, I will – Jagr Oct 06 '19 at 16:28

3 Answers3

1

You problems come from a misconception about data modeling in MongoDB, not uncommon for developers coming from other DBMS. Let me illustrate this with the example of how data modeling works with an RDBMS vs MongoDB (and a lot of the other NoSQL databases as well).

With an RDBMS, you identify your entities and their properties. Next, you identify the relations, normalize the data model and bang your had against the wall for a few to get the UPPER LEFT ABOVE AND BEYOND JOIN™ that will answer the questions arising from use case A. Then, you pretty much do the same for use case B.

With MongoDB, you would turn this upside down. Looking at your use cases, you would try to find out what information you need to answer the questions arising from the use case and then model your data so that those questions can get answered in the most efficient way.

Let us stick with your example of a contacts database. A few assumptions to be made here:

  1. Each user can have an arbitrary number of contacts.
  2. Each contact and each user need to be uniquely identified by something other than a name, because names can change and whatnot.
  3. Redundancy is not a bad thing.

With the first assumption, embedding contacts into a user document is out of question, since there is a document size limit. Regarding our second assumption: the uid field becomes not redundant, but simply useless, as there already is the _id field uniquely identifying the data set in question.

The use cases

Let us look at some use cases, which are simplified for the sake of the example, but it will give you the picture.

  1. Given a user, I want to find a single contact.
  2. Given a user, I want to find all of his contacts.
  3. Given a user, I want to find the details of his contact "John Doe"
  4. Given a contact, I want to edit it.
  5. Given a contact, I want to delete it.

The data models

User

{
  "_id": new ObjectId(),
  "name": new String(),
  "whatever": {}
}

Contact

{
  "_id": new ObjectId(),
  "contactOf": ObjectId(),
  "name": new String(),
  "phone": new String()
}

Obviously, contactOf refers to an ObjectId which must exist in the User collection.

The implementations

Given a user, I want to find a single contact.

If I have the user object, I have it's _id, and the query for a single contact becomes as easy as

db.contacts.findOne({"contactOf":self._id})

Given a user, I want to find all of his contacts.

Equally easy:

db.contacts.find({"contactOf":self._id})

Given a user, I want to find the details of his contact "John Doe"

db.contacts.find({"contactOf":self._id,"name":"John Doe"})

Now we have the contact one way or the other, including his/her/undecided/choose not to say _id, we can easily edit/delete it:

Given a contact, I want to edit it.

db.contacts.update({"_id":contact._id},{$set:{"name":"John F Doe"}})

I trust that by now you get an idea on how to delete John from the contacts of our user.

Notes

Indices

With your data model, you would have needed to add additional indices for the uid fields - which serves no purpose, as we found out. Furthermore, _id is indexed by default, so we make good use of this index. An additional index should be done on the contact collection, however:

db.contact.ensureIndex({"contactOf":1,"name":1})

Normalization

Not done here at all. The reasons for this are manifold, but the most important is that while John Doe might have only have the mobile number of "Mallory H Ousefriend", his wife Jane Doe might also have the email address "janes_naughty_boy@censored.com" - which at least Mallory surely would not want to pop up in John's contact list. So even if we had identity of a contact, you most likely would not want to reflect that.

Conclusion

With a little bit of data remodeling, we reduced the number of additional indices we need to 1, made the queries much simpler and circumvented the BSON document size limit. As for the performance, I guess we are talking of at least one order of magnitude.

Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89
  • Thank you for tips, I will implement this method. But how can I solve my question with it? I am very confused on how to implement this with my question – Jagr Oct 06 '19 at 18:47
  • @Jagr Long story short: you need to get back to the drawing board and start over. Then, the problem you describe in your question does not even occur. – Markus W Mahlberg Oct 06 '19 at 19:33
0

In the tutorial you mentioned above, they pass 2 parameters to the method, one for filter and one for projection but you just passed one, that's the difference. You can change your query to be like this:

Contact.contactModel.findOne( 
    {uid: self.uid},
    {contacts: {
      $elemMatch: {
        uid: {
          $exists: true,
          $ne: undefined,
        }
      }
    }}
 )
Cuong Le Ngoc
  • 11,595
  • 2
  • 17
  • 39
0

The agg framework makes filtering for existence of a field a little tricky. I believe the OP wants all docs where a field exists in an array of subdocs and then to return ONLY those subdocs where the field exists. The following should do the trick:

var inputtedUID = "0";  // doesn't matter
db.foo.aggregate(
[
// This $match finds the docs with our input UID:
{$match: {"uid": inputtedUID }}

// ... and the $addFields/$filter will strip out those entries in contacts where contacts.uid does NOT exist.  We wish we could use {cond: {$zz.name: {$exists:true} }} but
// we cannot use $exists here so we need the convoluted $ifNull treatment.  Note we
// overwrite the original contacts with the filtered contacts:
,{$addFields: {contacts: {$filter: {
                input: "$contacts",
                as: "zz",
                cond: {$ne: [ {$ifNull:["$$zz.uid",null]}, null]}
            }}
    }}
,{$limit:1}  // just get 1 like findOne()
 ]);

show(c);

{
    "_id" : 0,
    "uid" : 0,
    "contacts" : [
        {
            "uid" : "buzz",
            "n" : 1
        },
        {
            "uid" : "dave",
            "n" : 2
        }
    ]
}

Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33
  • I am really confused in the $filter section. Let me share my example. First I want to findOne document where the **uid** is equal to an inputted uid. Then in that document check in my **Contacts** array if the **uid** exists. If all those are met, then display all values/ – Jagr Oct 05 '19 at 16:42
  • Perhaps edit the original question and show a sample doc? I am unclear about where the `uid` match to input is related to the `Contacts` array. The language is important: saying "if the uid exists" is different than saying "if the uid FIELD exists." – Buzz Moschetti Oct 05 '19 at 16:45
  • I updated my question above, please take a look at my example :D – Jagr Oct 05 '19 at 17:01
  • Answer changed to reflect your needs. – Buzz Moschetti Oct 05 '19 at 17:14
  • Is this correct? https://imgur.com/a/dWZYt6J When I try this solution it returns no document – Jagr Oct 05 '19 at 17:27
  • Well.... My test with similar data and that agg pipeline works. I don't know what your invocation setup is but calling `aggregate()` yields a cursor. Your code passes that to `findOne()` which I don't understand. – Buzz Moschetti Oct 05 '19 at 18:19