mongoose - Query with mongodb to match the value of a string with each element of the array
巴扎黑
巴扎黑 2017-05-02 09:23:36
0
2
935

There is a document query and all the results are as follows:

db.order.find();

{ "_id" : ObjectId("58464c481dd68f2bcc8c280b"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d4deffe1c81858b7648f"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d557ee026d288000c922"), "teamId" : "581c33eb4d901f06f8ca4c65"}

Now there is a need to query the data matching the teamId with the elements in the array. For example, the condition array is as follows:

const array = ['580493941a81901a6cabe9b1'];

How should I write the query statement? You can query the following two pieces of data:

{ "_id" : ObjectId("58464c481dd68f2bcc8c280b"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d4deffe1c81858b7648f"), "teamId" : "580493941a81901a6cabe9b1"},

Please enlighten me, thank you.

巴扎黑
巴扎黑

reply all(2)
Peter_Zhu

Um, I still blame myself for being lazy.
I checked the documents just now and I immediately knew how to check/embarrassed

Post the query statement directly:

db.order.find({teamId: {$in: ['580493941a81901a6cabe9b1']}});

If you encounter a problem, check the documentation first.

仅有的幸福

When I first saw this problem, I thought it should be handled using the $in operator. I thought it was a relatively simple problem.

Looking at your question carefully, the data in the array is the string of _id. I am wondering if there is an input error and whether it is necessary to compare the values ​​of _id and array.

Before comparison, the strings in the array need to be converted to ObjectId.

for (i in arraySrc) {arrayTgt.push(ObjectId(ArraySrc[i]));}

Then

db.order.find({_id : { $in : arrayTgt}})

For reference.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template