简体   繁体   中英

How to extract an array of fields from an array of JSON documents?

I have 2 mongodb collections, stu_creds and stu_profile . I first want to retrieve all the student records from stu_creds where stu_pref_contact is the email and then for those stu_id s I want to retrieve the complete profile from stu_profile . The problem is, the first query returns an array of JSON documents, with each document holding one field, the stu_id . Here is my query and the result:

db.stu_creds.find({"stu_pref_contact" : "email"}, {'_id' : 1})

Result:

[{ "_id" : ObjectId("51927cc93080baac04000001") },
{ "_id" : ObjectId("51927d7b3080baac04000002") },
{ "_id" : ObjectId("519bb011c5c5035b2a000002") },
{ "_id" : ObjectId("519ce3d09f047a192b000010") },
{ "_id" : ObjectId("519e6dc0f919cfdc66000003") },
{ "_id" : ObjectId("51b39be0c74f0e3d23000012") },
{ "_id" : ObjectId("51b39ca9c74f0e3d23000014") },
{ "_id" : ObjectId("51b39cb7c74f0e3d23000016") },
{ "_id" : ObjectId("51b39e87c74f0e3d23000018") },
{ "_id" : ObjectId("51b39f2fc74f0e3d2300001a") },
{ "_id" : ObjectId("51b39f47c74f0e3d2300001c") },
{ "_id" : ObjectId("518d454deb1e3a525e000009") },
{ "_id" : ObjectId("51bc8381dd10286e5b000002") },
{ "_id" : ObjectId("51bc83f7dd10286e5b000004") },
{ "_id" : ObjectId("51bc85cbdd10286e5b000006") },
{ "_id" : ObjectId("51bc8630dd10286e5b000008") },
{ "_id" : ObjectId("51bc8991dd10286e5b00000a") },
{ "_id" : ObjectId("51bc8a43dd10286e5b00000c") },
{ "_id" : ObjectId("51bc8a7ddd10286e5b00000e") },
{ "_id" : ObjectId("51bc8acadd10286e5b000010") }]

The thing is, I don't think I can use the above array as part of an $in clause for my 2nd query to retrieve the student profiles. I have to walk thru the array and and create a new array which is just an array of object ids rather than an array of JSON docs.

Is there an easier way to do this?

Use Array.map ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ). This allows you to perform a transform on each element of the array, returning you a new array of the transformed items.

var arrayOfIds = result.map(function(item){ return item._id; });

Array.map was introduced in ECMAScript 5. If you're using node.js, a modern browser, or an Array polyfill, it should be available to use.

Ummm, am I missing something or is all you want the following:

var results = [];
for(var i = 0; i < yourArray.length; i++) {
    results.push(yourArray[i]._id);
}

You could use $or :

db.stu_profile.find({ $or : results }) // `results` is your list of ObjectId's

But it's considerably slower than $in , so I would suggest using one of the other answers ;)

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