简体   繁体   中英

Mongodb check If field exists in an sub-document of an array

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在此处输入图像描述 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 contacts 1 doesn't have a uid field.

Contact.contactModel.findOne({$and: [

        {uid: self.uid},

        {contacts: {

          $elemMatch: {

            uid: {

              $exists: true,

              $ne: undefined,

            }

          }

        }}

      ]}

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,
        }
      }
    }}
 )

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
        }
    ]
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM